如何在R中通过匹配ID合并行数不同的多个DataFrame
合并多时间区间DataFrame并保留唯一属性列
方法1:使用dplyr处理2个数据框
先加载依赖包,执行合并逻辑:
library(dplyr) # 合并df1和df2 merged_df <- full_join(df1, df2, by = "id") %>% # 合并race和age列,保留唯一值 mutate( race = coalesce(race.x, race.y), age = coalesce(age.x, age.y) ) %>% # 按需求排列列顺序 select(id, race, age, starts_with("one_"), starts_with("two_"), starts_with("three_"))
运行后得到的结果与你期望的输出完全一致:
id race age one_T1 two_T1 three_T1 one_T2 two_T2 three_T2 1 1 Black 26 1 1 0 1 1 0 2 2 White 24 0 0 0 0 0 0 3 3 Asian 33 1 1 0 NA NA NA 4 4 White 45 1 1 1 1 1 0 5 5 Black 65 1 0 1 1 1 1 6 6 Indigenous 21 NA NA NA 1 0 1
方法2:使用dplyr+purrr批量处理7个数据框
如果需要合并7个DataFrame(df1到df7),可以用批量连接逻辑:
library(dplyr) library(purrr) # 将所有数据框放入列表 df_list <- list(df1, df2, df3, df4, df5, df6, df7) # 批量合并并整理数据 final_df <- df_list %>% # 对列表中所有数据框执行全连接 reduce(full_join, by = "id") %>% # 合并所有race和age列,保留唯一值 mutate( race = coalesce(!!!syms(str_subset(names(.), "^race"))), age = coalesce(!!!syms(str_subset(names(.), "^age"))) ) %>% # 按需求排列列 select(id, race, age, starts_with("one_"), starts_with("two_"), starts_with("three_"))
方法3:使用data.table(适合大数据场景)
若数据量较大,data.table的合并效率更高:
library(data.table) # 转换为data.table格式 setDT(df1) setDT(df2) # 全连接合并 merged_dt <- merge(df1, df2, by = "id", all = TRUE) # 合并race和age列并删除冗余列 merged_dt[, `:=`( race = fcoalesce(race.x, race.y), age = fcoalesce(age.x, age.y) )][, c("race.x", "race.y", "age.x", "age.y") := NULL] # 重新设置列顺序 setcolorder(merged_dt, c("id", "race", "age", "one_T1", "two_T1", "three_T1", "one_T2", "two_T2", "three_T2"))
说明
- 所有方法默认同一个id的race和age在不同时间区间数据中保持一致,若存在不一致的情况,需额外添加逻辑处理(比如取首次出现的值或校验)。
full_join(或data.table的merge(all=TRUE))会自动为不存在的时间变量填充NA,符合需求。
内容的提问来源于stack exchange,提问作者user21027866
相关产品推荐
相关产品推荐

