简体   繁体   中英

Create new column in data.frames within a list and populate it with specific repeating values

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM