如何在R中基于含向量的列合并两个数据集?
R语言合并含向量列的数据集解决方案
示例数据
df1 <- data.frame(place = c("a", "b", "c")) df1$stops <- list(c(1,2,3), c(2,3,4), c(3,4,5)) df2 <- data.frame(stops = c(1,2,3,4,5)) df2$trips <- list(c(343,353), c(492, 4332), c(375, 346), c(110, 109), c(267, 268))
解决方案
方法1:使用tidyverse工具(dplyr + purrr)
加载依赖包后,遍历df1的stops列,匹配df2中对应stop的trips并合并:
library(dplyr) library(purrr) result <- df1 %>% mutate( trips = map(stops, ~ unlist(df2$trips[df2$stops %in% .x])) )
方法2:Base R实现
无需额外包,用lapply完成相同逻辑:
df1$trips <- lapply(df1$stops, function(x) { unlist(df2$trips[df2$stops %in% x]) })
结果验证
执行后得到的数据集每行对应一个地点,trips列是该地点所有关联stop对应的trips合并后的向量:
> print(result) place stops trips 1 a 1, 2, 3 343, 353, 492, 4332, 375, 346 2 b 2, 3, 4 492, 4332, 375, 346, 110, 109 3 c 3, 4, 5 375, 346, 110, 109, 267, 268
内容的提问来源于stack exchange,提问作者Monelisa
相关产品推荐
相关产品推荐

