首页 > 解决方案 > 当其中一列是列表时合并,生成一个新列,即列表

问题描述

我有两个要合并的数据集。我想用作合并键的列之一具有列表中的值。如果这些值中的任何一个出现在第二个数据集的列中,我希望将另一列中的值合并到第一个数据集中——这可能意味着有多个值,应该以列表的形式呈现。

这很难解释,但希望这个示例数据更清楚。

示例数据

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))))

标签: rmergedata.table

解决方案


我能想到的最简单的方法是,首先取消列出孩子,然后合并,然后再次列出:

mother1 <- mother_dt[,.(children=unlist(children)),by=mother]
mother1[child_dt,on=c(children='child')][,.(children=list(children),age=list(age)),by=mother]

推荐阅读