在列表中的 data.frames 中创建新列并用特定的重复值填充它

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

这是我的列表示例(我在真实列表中实际上有 > 2,000 df):

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)

我需要为列表中的每个 data.frame 创建一个新列,并用特定数字填充每个列。

numbers = c(100, 200)

所以我的输出应该是:

> 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

使用 lapply 我能够为每个 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 

但我不知道如何用我的数字向量填充列。

谢谢

为了同时迭代data.frames的列表和数字向量,使用Map()。例如

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