Hope this question can help other R users too.
There is a list with several objects (initial data frames), all with the same structure. The goal is to melt each object and replace the name of the third variable with the name of the corresponding object, using lapply.
The data frames are:
gdp <- data.frame(date = as.Date(c('2010-03-31','2010-06-30','2010-09-30','2010-12-31')),
id1 = rnorm(4), id2 = rnorm(4), id3 = rnorm(4));
employ <- data.frame(date = as.Date(c('2010-03-31','2010-06-30','2010-09-30','2010-12-31')),
id1 = rnorm(4), id2 = rnorm(4), id3 = rnorm(4));
fdi <- data.frame(date = as.Date(c('2010-03-31','2010-06-30','2010-09-30','2010-12-31')),
id1 = rnorm(4), id2 = rnorm(4), id3 = rnorm(4));
The list including the data frames is:
data.list <- list(gdp=gdp, employ=employ, fdi=fdi);
The attempt towards melting the different objects in the list into a panel data structure (melt using id=c("date")), and replacing the name of the third variable (named value, after melting) with the name of the respective object (that is, gdp, employ and fdi), is as follows:
data.list <- lapply(data.list, function(x) {
x <- melt(x, id = c("date"));
setnames(x, c("date", "id", paste(names(data.list[x])))); x});
However, this results in the following error message:
"Error in data.list[x] : invalid subscript type 'list'"
Thanks for sharing your knowledge!
{and as there was no indentation, i thought it as creating separate object.