简体   繁体   English

R - 通过循环遍历向量中的元素,将列添加到列表中的数据帧

[英]R - Add columns to dataframes in list by looping through elements in a vector

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 这个问题与我的类似,但我想迭代地将向量中的每个元素添加到相应的数据帧作为新列: R - 循环中多个数据帧的新变量

Here's sample data: 这是样本数据:

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: 我想这样做但是认为可能还有一些方法可以循环(或者说是lapply)我还没弄清楚:

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! 谢谢!

The full answer based on @@thelatemail comment: 基于@@ thelatemail评论的完整答案:

The function Map(cbind, data_list, year=year) should do the job. 函数Map(cbind, data_list, year=year)应该完成这项工作。 Step by step: 一步步:

  • Map function indicates a loop through elements in a list Map函数指示列表中元素的循环
  • cbind attaches newly created column cbind附加新创建的列
  • year = years creates new column named year based on elements in a vector years year = years基于向量years元素创建名为year的新列

Having your dummy example: 有你的假例子:

# 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)

The output you wish: 你想要的输出:

$`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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM