1

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

aaaaa
  • 149
  • 2
  • 18
  • 44

1 Answers1

6

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
MrFlick
  • 195,160
  • 17
  • 277
  • 295