I have a list of 11 dataframe, and want to create a new column within each dataframe and populate the column with year as c(2005:2015)
. The problem is that it iterates 11 items (Years) for 255 rows in a dataframe and hence shows error. What I want that it should not iterate for rows in dataframes, but iterate for dataframes with in list. So that first dataframe has 255 rows of Year showing value 2005 and so on.
I have tried the following code, but just as I said. It iterates within dataframe instead I want it to populate just one value per dataframe and iterate on the list not one level below.
tf2 <- lapply(tf2, function(x) mutate(x, YEAR = c(2005:2015)))
Note: mutate
cannot directly be applied to object of the class list
.
I am trying something new like this, but my code is erroneous it needs to be corrected.
year <- c(2005:2015)
ChangeYears = function(x)
{
for i in 1:length(tf2)
{
x[i] <- lapply(mutate(YEAR = c(year[i])))
}
}
tf2 <- lapply(tf2, ChangeYears)
Based on the modifications suggested by @GSW I am trying this
ChangeYears = function(x){
for(i in 1:11) {
x[[i]] = cbind(x[[i]], Year=2004+i) }
}
lapply(tf2, ChangeYears)
But I am getting the following error.
Error in .subset2(x, i, exact = exact) : subscript out of bounds
.