如何在R语言中从数据框列表选取列并合并成新数据框?
批量处理列表中的DataFrame并合并
我有一个名为df.list的对象,其中包含多个DataFrame,以下是两个示例:
> dput(df.list$GF.1.GULUPA.1.F1) structure(list(Evaluacion2 = c("5.1", "5.2"), Sistema = c(1, 1), Fertilizacion = c("F1", "F1"), Asocio = c("GF", "GF"), Cultivo = c("GULUPA", "GULUPA"), Bloque = c(1, 1), `Altura de planta` = c(3.3, 5.1)), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame")) > dput(df.list$MF.1.MORA.1.F1) structure(list(Evaluacion2 = c("1.1", "1.2", "3.1", "3.2", "4.1", "4.2", "5.1", "5.2"), Sistema = c(1, 1, 1, 1, 1, 1, 1, 1), Fertilizacion = c("F1", "F1", "F1", "F1", "F1", "F1", "F1", "F1"), Asocio = c("MF", "MF", "MF", "MF", "MF", "MF", "MF", "MF"), Cultivo = c("MORA", "MORA", "MORA", "MORA", "MORA", "MORA", "MORA", "MORA"), Bloque = c(1, 1, 1, 1, 1, 1, 1, 1), `Altura de planta` = c(11.3, 11.7, 42, 62, 57.1, 51.3, 90.1, 70.2)), row.names = c(NA, -8L), class = c("tbl_df", "tbl", "data.frame"))
我需要提取植株高度列(Altura de planta)的值,并根据DataFrame的名称为该列命名,示例操作如下:
df.a<-select(df.list$GF.1.GULUPA.1.F1, c("Evaluacion2", "Altura de planta")) df.b<-select(df.list$MF.1.MORA.1.F1, c("Evaluacion2", "Altura de planta")) names(df.a)<-c("Evaluacion2", "GF.1.GULUPA.1.F1 Altura de planta") names(df.b)<- c("Evaluacion2", "MF.1.MORA.1.F1 Altura de planta") df.j<-df.a%>%full_join(df.b) > dput(df.j) structure(list(Evaluacion2 = c("5.1", "5.2", "1.1", "1.2", "3.1", "3.2", "4.1", "4.2"), `GF.1.GULUPA.1.F1 Altura de planta` = c(3.3, 5.1, NA, NA, NA, NA, NA, NA), `MF.1.MORA.1.F1 Altura de planta` = c(90.1, 70.2, 11.3, 11.7, 42, 62, 57.1, 51.3)), row.names = c(NA, -8L ), class = c("tbl_df", "tbl", "data.frame"))
我需要对df.list中的所有DataFrame执行上述操作,请求帮助,非常感谢!
解决方案
方法1:使用tidyverse工具链(推荐)
借助purrr和dplyr实现批量处理,代码简洁高效:
library(dplyr) library(purrr) # 遍历列表处理每个DataFrame processed_dfs <- imap(df.list, function(df, df_name) { df %>% select(Evaluacion2, `Altura de planta`) %>% rename(!!paste0(df_name, " Altura de planta") := `Altura de planta`) }) # 全连接所有处理后的DataFrame df.j <- reduce(processed_dfs, full_join, by = "Evaluacion2")
代码说明:
imap():遍历列表时同时获取每个DataFrame及其名称(df_name)select():保留关键列Evaluacion2和目标高度列rename():通过!!实现动态列名,拼接DataFrame名称和原列名reduce():自动完成所有DataFrame的全连接,无需手动逐个合并
方法2:基础R实现
如果不想加载额外包,可使用基础R循环完成:
# 初始化合并结果 df.j <- NULL # 遍历列表中的每个DataFrame for (df_name in names(df.list)) { current_df <- df.list[[df_name]] # 选择指定列并重命名 temp_df <- current_df[, c("Evaluacion2", "Altura de planta")] colnames(temp_df)[2] <- paste0(df_name, " Altura de planta") # 合并到主结果 if (is.null(df.j)) { df.j <- temp_df } else { df.j <- merge(df.j, temp_df, by = "Evaluacion2", all = TRUE) } }
内容的提问来源于stack exchange,提问作者Alex Velasquez
相关产品推荐
相关产品推荐

