【发布时间】:2023-03-12 20:20:01
【问题描述】:
我有一个data.table,它的每一行、一个年龄列和 2 列都有唯一ID,其中包含年龄的置信区间。我想要做的是合并具有重叠 CI 的行,因此返回的 CI 是重叠的最小/最大值。
ID Age AgeMax AgeMin
1: 2 48073 49213 46933
2: 3 49002 49638 48366
3: 7 44297 44706 43888
此示例的返回结果将是:
ID Age AgeMax AgeMin
2 48409 49638 46933
7 44297 44706 43888
由于 ID 2 和 3 在 AgeMax 和 AgeMin 中有重叠的值。 ID == 2 的 AgeMax 小于 ID == 3 的 AgeMax,但大于 ID == 3 的 AgeMin,因此它们重叠。 ID 7 不与其他行重叠,因此按原样返回。
我实际上并不介意返回的 ID 和 Age 是什么,只要它来自重叠的 ID 之一
我的尝试如下,但我没有得到正确的结果
library(data.table)
# sequence of years
step <- 10
window <- 30
startYear <- -60000+(0.5*window)
endYear <- 0-(0.5*window)
yrSeq <- abs(seq(startYear, endYear, step))
# Example DT
DT <- structure(list(ID = c(2L, 3L, 7L), Age = c(48073L, 49002L, 44297L
), AgeMax = c(49213L, 49638L, 44706L), AgeMin = c(46933L, 48366L,
43888L)), row.names = c(NA, -3L), class = c("data.table", "data.frame"
))
# split into a list to expand the CI's
s <- split(DT, DT$ID)
# Expand the CI's, to the nearest year in the seq
# merge back into a DT
d_seq <- rbindlist(lapply(s, function(x) {
data.table(ID = x$ID, Yr = yrSeq[between(yrSeq, x$AgeMin, x$AgeMax)])}))
# remove duplicated years and return min and max years for each ID
d_seq <- d_seq[!duplicated(d_seq$Yr),]
d_seq <- d_seq[, .(AgeMin = min(Yr), AgeMax = max(Yr)), by = ID]
# merge with the original DT and select columns
DT <- merge(DT, d_seq, by = "ID")
DT <- DT[, c(1,2,5,6)]
不幸的是,这不起作用,因为 ID == 3 被返回,即使它与 ID == 2 重叠(如上所示),现在 ID == 2 的 AgeMin 和 AgeMax 不包括年龄那个ID!
ID Age AgeMin AgeMax
1: 2 48073 46935 49205
2: 3 49002 49215 49635
3: 7 44297 43895 44705
我确定我想太多了,必须有一种简单的方法可以返回我需要的东西,不幸的是我找不到任何解决方案。
这是一个额外的示例data.table 进行测试。
testDT <- structure(list(ID = c(54L, 57L, 58L, 60L, 61L, 62L, 64L, 180L
), Age = c(14219L, 13989L, 13883L, 13482L, 13403L, 13383L, 13340L,
13994L), AgeMax = c(14343L, 14087L, 13972L, 13540L, 13465L, 13442L,
13407L, 14083L), AgeMin = c(14095L, 13891L, 13794L, 13424L, 13341L,
13324L, 13273L, 13905L)), row.names = c(NA, -8L), class = c("data.table",
"data.frame"))
【问题讨论】:
标签: r merge data.table overlap