-2

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.

ambrish dhaka
  • 689
  • 7
  • 27
  • Please add sample data, current and expected output(visually ie copy and paste what they (should) look like). Use `dput` for data. See [this post](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for details. – NelsonGon Jun 15 '19 at 13:25
  • Sample data won't help as the size of data is 18.7 MB. – ambrish dhaka Jun 15 '19 at 13:28
  • Please read the above post and update your post. Maybe it's just me but I think having sample data and a **visual** of your current and expected output makes it easier to understand what the goal is. – NelsonGon Jun 15 '19 at 13:28
  • can you help in getting the right code for the new thing. – ambrish dhaka Jun 15 '19 at 13:31

1 Answers1

1

Here is a simple example.

## A list of 11 data frames
tf2 = list()
for(i in 1:11) {
    tf2[[i]] = data.frame(x = rnorm(10), y = rnorm(10)) }


## Add a year column to each. 
for(i in 1:11) {
    tf2[[i]] = cbind(tf2[[i]], Year=2004+i) }

Addition:

This modifies your proposed function so that it works.

ChangeYears = function(x){
  for(i in 1:11) {
    x[[i]] = cbind(x[[i]], Year=2004+i) }
  x
}

tf2 = ChangeYears(tf2)
G5W
  • 36,531
  • 10
  • 47
  • 80