[英]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): 这是我的列表的一个示例(实际中我有> 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)
I need to create a new column for each data.frame within the list and populate each column with a specific number. 我需要为列表中的每个data.frame创建一个新列,并为每个列填充一个特定的数字。
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: 使用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
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()
. 为了同时迭代data.frames列表和数字矢量,请使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.