[英]Assign new columns to a list of dataframes from a second dataframe in R
I have a list of dataframes df_list
and a second dataframe df_new
.我有一个数据帧列表df_list
和第二个数据帧df_new
。 I want to add the 1st column a
of df_new
into the 1st dataframe mtcars1
in the list df_list
, the 2nd column b
of df_new
into the 2nd dataframe mtcars2
in the list df_list
, and so on.我想第一列加a
的df_new
到第一数据帧mtcars1
列表df_list
,第二列b
的df_new
进入第二个数据帧mtcars2
列表df_list
,等等。
The expected result: In the df_list
, mtcars1
will have a new column a
from df_new
, mtcars2
will have a new column b
from df_new
, mtcars3
will have a new column c
from df_new
, mtcars4
will have a new column c
from df_new
.预期结果:在df_list
, mtcars1
将有一个来自df_new
的新列a
, mtcars2
将有一个来自df_new
的新列b
, mtcars3
将有一个来自df_new
的新列c
, mtcars4
将有一个来自df_new
的新列c
。
What's the best way to do this in a function or loop?在函数或循环中执行此操作的最佳方法是什么?
library(tidyverse)
df_list <- list(mtcars, mtcars, mtcars, mtcars)
names(df_list) <- c("mtcars1", "mtcars2", "mtcars3", "mtcars4")
df_new <- mtcars[1:4] %>% rename(a = mpg, b = cyl, c = disp, d = hp)
Does this work for you?这对你有用吗?
for(i in 1:4){
df_list[[i]] = cbind(df_list[[i]], df_new[,i])}
Using Map :使用地图:
Map(cbind, df_list, df_new)
If we need to keep the names, then write custom function:如果我们需要保留名称,则编写自定义函数:
myCbind <- function(x, y){
d <- cbind(x, df_new[[ y ]])
colnames(d)[ ncol(d) ] <- y
d
}
Map(myCbind, df_list, colnames(df_new))
Check the names:检查名称:
res <- Map(myCbind, df_list, colnames(df_new))
sapply(res, function(i) tail(colnames(i), 1))
# mtcars1 mtcars2 mtcars3 mtcars4
# "a" "b" "c" "d"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.