R - 通过循环遍历向量中的元素将列添加到列表中的数据帧 [英] R - Add columns to dataframes in list by looping through elements in a vector
问题描述
我正在使用多个数据集,这些数据集多年来测量相同的变量.我正在尝试向每个数据集添加一个年份变量,但更一般地说,我想遍历向量中的元素并将每个元素添加为数据框列表中的新列.这个问题与我的相似,但我想迭代地将向量中的每个元素添加到相应的数据框中作为一个新列:R - 多个数据框上的新变量循环中
I am working with several datasets that measure the same variables over many years. I am trying to add a year variable to each dataset, but more generally I want to loop through elements in a vector and add each as a new column in a list of dataframes. This question was similar to mine but I want to iteratively add each element in a vector to the corresponding dataframe as a new column: R - New variables over several data frames in a loop
以下是示例数据:
year <- c(1:3)
data1 <- data.frame(var1 = c(1:5))
data2 <- data.frame(var1 = c(11:15))
data3 <- data.frame(var1 = c(21:25))
data_list <- list(data1 = data1, data2 = data2, data3 = data3)
我想这样做,但认为可能有某种我还没有弄清楚的循环(或 lapply)方法:
I want to do this but think there's probably some way to loop (or lapply) that I haven't been able to figure out yet:
data1$year <- year[1]
data2$year <- year[2]
data3$year <- year[3]
由于我有多年的工作经验和数据集,如果有一个更有效的解决方案会很棒.谢谢!
Since I have many years and datasets to work with, it'd be great to have a more efficient solution. Thanks!
推荐答案
完整答案基于@@thelatemail 评论:
The full answer based on @@thelatemail comment:
函数 Map(cbind, data_list, year=year)
应该可以完成这项工作.一步一步:
The function Map(cbind, data_list, year=year)
should do the job. Step by step:
Map
函数表示循环遍历列表中的元素cbind
附加新创建的列year = years
根据向量years
中的元素创建名为
year
的新列Map
function indicates a loop through elements in a listcbind
attaches newly created columnyear = years
creates new column namedyear
based on elements in a vectoryears
有你的虚拟示例:
# vector of values you wish to add
years <- c(1:3) # changed to plural to indicate vector of values rather than single value
# make dummy list of dataframes
data1 <- data.frame(var1 = c(1:5))
data2 <- data.frame(var1 = c(11:15))
data3 <- data.frame(var1 = c(21:25))
data_list <- list(data1 = data1, data2 = data2, data3 = data3)
# Loop through list of dataframes and to each dataframe add a new column
Map(cbind, data_list, year=years)
你想要的输出:
$`data1`
var1 year
1 1 1
2 2 1
3 3 1
4 4 1
5 5 1
$data2
var1 year
1 11 2
2 12 2
3 13 2
4 14 2
5 15 2
$data3
var1 year
1 21 3
2 22 3
3 23 3
4 24 3
5 25 3
这篇关于R - 通过循环遍历向量中的元素将列添加到列表中的数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!