简体   繁体   English

将新列分配给 R 中第二个数据框的数据框列表

[英]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.我想第一列加adf_new到第一数据帧mtcars1列表df_list ,第二列bdf_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_listmtcars1将有一个来自df_new的新列amtcars2将有一个来自df_new的新列bmtcars3将有一个来自df_new的新列cmtcars4将有一个来自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.

相关问题 将列转置为数据帧列表中的行并将其写入 R 中的新 dataframe - transpose a columns to row in a list of dataframes and write it to a new dataframe in R 按列将 R Dataframe 拆分为许多新数据帧 - Split R Dataframe into many new dataframes by columns 自动为数据框列表创建新列 - R - Automating the creation of new columns for a list of dataframes - R 遍历多个数据帧(csv),添加一个新列并分配一个由原始 dataframe 名称驱动的值 R - Iterate through multiple dataframes (csv), add a new column and assign a value drived from original dataframe names in R 将R中2个不同数据框的列名分配给新的空数据框 - Assign column names to a new empty dataframe from column names of 2 different dataframes in R 查找在两个数据帧中匹配的两列,并使用 R 将数据帧 2 中的第三列放入数据帧 1 中的新列中 - Find two columns that match in two dataframes and put third column from dataframe 2 into a new column in dataframe 1 using R 如何在 R 的 dataframe 的新列中分配列表 - How assign a list in a new column of a dataframe in R 如何通过合并 R 中不同数据框中具有相同名称的列来创建新的 dataframe? - How to create a new dataframe by merging columns with identical names from different dataframes in R? 如何通过第三个关键变量 (R) 将来自不同数据帧的两列合并到新的数据帧中 - How to merge two columns from different dataframes into a new dataframe by a third key variable (R) 如何将新值从lapply分配给列表中数据框的新列 - How to assign new values from lapply to new column in dataframes in list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM