r - 当其中一列是列表时合并,生成一个新列,即列表
问题描述
我有两个要合并的数据集。我想用作合并键的列之一具有列表中的值。如果这些值中的任何一个出现在第二个数据集的列中,我希望将另一列中的值合并到第一个数据集中——这可能意味着有多个值,应该以列表的形式呈现。
这很难解释,但希望这个示例数据更清楚。
示例数据
library(data.table)
mother_dt <- data.table(mother = c("Penny", "Penny", "Anya", "Sam", "Sam", "Sam"),
child = c("Violet", "Prudence", "Erika", "Jake", "Wolf", "Red"))
mother_dt [, children := .(list(unique(child))), by = mother]
mother_dt [, child := NULL]
mother_dt <- unique(mother_dt , by = "mother")
child_dt <- data.table(child = c("Violet", "Prudence", "Erika", "Jake", "Wolf", "Red"),
age = c(10, 8, 9, 6, 5, 2))
例如,我的新数据集中的第一行的列中将包含“Penny”,mother
列中包含“Violet”和“Prudence”的children
列表,列中包含 10 和 8 的age
列表。
我尝试了以下方法:
combined_dt <- mother_dt[, child_age := ifelse(child_dt$child %in% children,
.(list(unique(child_dt$age))), NA)
但这仅包含最后一行中所有年龄的列表。
我很欣赏这可能是非常不寻常的行为,但有没有办法实现它?
编辑:最终的数据表如下所示:
final_dt <- data.table(mother = c("Penny", "Anya", "Sam"),
children = c(list(c("Violet", "Prudence")), list(c("Erika")), list(c("Jake", "Wolf", "Red"))),
age = c(list(c(10, 8)), list(c(9)), list(c(6, 5, 2))))
解决方案
我能想到的最简单的方法是,首先取消列出孩子,然后合并,然后再次列出:
mother1 <- mother_dt[,.(children=unlist(children)),by=mother]
mother1[child_dt,on=c(children='child')][,.(children=list(children),age=list(age)),by=mother]
推荐阅读
- powershell - 在 powershell 中自动修改 .csv 文件
- unit-testing - 交叉编译项目的 CTest 单元测试
- c# - 在 C# 中,我如何浏览 Google 表格文档并写入特定单元格
- java - Primefaces ajax actionListener 未在 p:selectOneMenu 中调用
- java - 如何在数组/数组列表中存储和读取扫描仪输入?
- flutter - Flutter 问题:从上下文开始找不到 MediaQuery 祖先
- benchmarking - 完整性 RTOS 延迟
- reactjs - Gatsby:初始页面加载后获取 json 文件
- python - 如何在具有多个数据库的一个应用程序中迁移/进行迁移
- mongodb - 关于mongodb如何选择索引或者$or查询的问题