R-通过遍历向量中的元素将列添加到列表中的数据框 [英] R - Add columns to dataframes in list by looping through elements in a vector
问题描述
我正在使用多个数据集,这些数据集多年来测量了相同的变量.我正在尝试为每个数据集添加year变量,但更一般而言,我想遍历向量中的元素,并将每个元素添加为数据帧列表中的新列.这个问题类似于我的问题,但我想将向量中的每个元素作为新列迭代添加到相应的数据帧中: 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)
我想这样做,但是认为可能还有一些我还无法弄清楚的循环方式(或不适当地适用):
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屋!