1
votes

Here an example of my list (I actually have > 2,000 df in the real one):

df1 = read.table(text = 'a b
1 66
1 999
23 89', header = TRUE)

df2 = read.table(text = 'a b
99 61
32 99
83 19', header = TRUE)

lst = list(df1, df2)

I need to create a new column for each data.frame within the list and populate each column with a specific number.

numbers = c(100, 200)

so my output should be:

> lst
[[1]]
   a   b  new_col
1  1  66   100
2  1 999   100
3 23  89   100

[[2]]
   a  b  new_col
1 99 61   200
2 32 99   200
3 83 19   200

With lapply I was able to create a new blank column for each data.frame:

lst = lapply(lst, cbind, new_col = '')

> lst
[[1]]
   a   b new_col
1  1  66        
2  1 999        
3 23  89        

[[2]]
   a  b new_col
1 99 61        
2 32 99        
3 83 19 

But I don't know how to populate the columns with my vector of numbers.

Thanks

1
Please ask a new question with your reproducible list and vector instead of updating this one. Editing this one might invalidate the correct answer.Rich Scriven
Hi the new list is basically the same as the old one.why I get this error?aaaaa
Can't say because it works fine with the current data.Rich Scriven

1 Answers

6
votes

In order to iterate both the list of data.frames and vector of numbers at the same time, use Map(). For example

Map(cbind, lst, new_col=numbers)
# [[1]]
#    a   b new_col
# 1  1  66     100
# 2  1 999     100
# 3 23  89     100
# 
# [[2]]
#    a  b new_col
# 1 99 61     200
# 2 32 99     200
# 3 83 19     200