【发布时间】:2019-06-19 18:12:09
【问题描述】:
我在 R 中有两个数据表,它们具有相同的列(编号、名称和顺序)和一个 ID,如下所示:
library(data.table)
dt1 <- data.table(ids = c(1, 2, 5), col1 = c("A", "B", "F"), col2 = c("B", "F", "G"))
dt2 <- data.table(ids = c(2, 1, 6, 5), col1 = c("B", "A", "K", "L"), col2 = c("F", "G", "M", "G"))
> dt1
ids col1 col2
1: 1 A B
2: 2 B F
3: 5 F G
> dt2
ids col1 col2
1: 2 B F
2: 1 A G
3: 6 K M
4: 5 L G
我想知道每一列有多少(常见)ID 具有相同的值。例如,对于 col1,我们有:对于 ID1,两个值都是 A,对于 ID2,两个值都是 B,对于 ID5,值不同,因此该列的最终结果是 2。 我有以下解决方案:
joint_dt <- merge(dt1, dt2, by = "ids", suffixes = c("", "_old"))
comp_res <- mapply(function(x, y) sum(x == y), joint_dt[, 2:ncol(dt1)], joint_dt[, (ncol(dt1) + 1):ncol(joint_dt)])
> comp_res
col1 col2
2 2
这是做我想做的最好的方法,还是我错过了一些专门为此而设计的包或功能?
【问题讨论】:
标签: r dplyr data.table