问题
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
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:
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!
回答1:
The full answer based on @@thelatemail comment:
The function Map(cbind, data_list, year=year)
should do the job. Step by step:
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
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
来源:https://stackoverflow.com/questions/40251202/r-add-columns-to-dataframes-in-list-by-looping-through-elements-in-a-vector