简体   繁体   English

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

[英]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.

相关问题 列表-在data.frames中创建新列,并将字母分配给特定数字 - list - create new column in data.frames with letters assigned to specific numbers 将值的新列设置为data.frames列表 - set new column of values to list of data.frames 从 data.frames 列表中创建具有特定行的 data.frames 列表 - Create list of data.frames with specific rows from list of data.frames 如何通过系统地重新排列现有data.frames列中的列来创建新的data.frames列表 - how to create a new list of data.frames by systematically rearranging columns from an existing list of data.frames 从系数转换为数值将列表中data.frames中的一列转换为数字 - Convert from factor to numeric a column in data.frames within a list 列表-使用lapply重命名特定的data.frames列 - list - rename specific data.frames column with lapply R-将功能应用于相似数据列表中的特定列 - R - Apply a function to specific column in a list of similar data.frames 对带有data.frames列表的lapply中的带有特定值的向量使用predict() - Using predict() with a vector of specific values in lapply for a list of data.frames 根据来自两个 data.frames 的匹配值在 R 中创建新列表 - Create new list in R based on matching values from two data.frames 使用lapply在data.frames列表上创建列值的条件和 - Using lapply to create a conditional sum of column values over a list of data.frames
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM