r-如何根据组中特定列的结果中的日期范围筛选行



问题

我有四列数据(ID),完成测试的日期(TestDT),一列是感兴趣的测试的数字结果(Test1),另一列是不同感兴趣测试的数值结果(Test2)。

ID  TestDT      Test1   Test2
1   2011-03-02  23       NA
2   2011-03-14  NA       16
2   2011-03-15  NA       52
2   2011-11-22  24       NA
2   2011-12-12  NA       77
3   2009-03-02  NA       23
3   2009-05-02  15       NA
3   2011-15-02  NA       66
4   2017-07-03  NA       22

所需结果

我想得到在3个月时间段内(即在测试1之前或之后)发生的任何测试2的平均结果

ID  TestDT      Test1   Test2 Av_of_test2_within_range
1   2011-03-02  23       NA    34
2   2011-11-22  24       NA    77
3   2009-05-02  15       NA    23

我很难过滤在时间范围内发生的Test2结果

尝试

我尝试使用tibbletime包中的filter_time,如下所示:

library(tibbletime)
FB <- as_tbl_time(myData, index = TestDT)
FB %>% group_by(ID) %>%filter_time(TestDT ~ TestDT+84)

但是得到错误:

Error: Problem with `filter()` input `..1`.
x object 'TestDT' not found
i Input `..1` is `{ ... }`.
The error occured in group 1: 

data.table具有foverlaps函数,用于合并日期范围内的两个数据集。

您需要将数据分为test1和test2,并执行以下操作:

library(data.table)
df <- read.table(text = "ID  TestDT      Test1   Test2
1   2011-03-02  23       NA
2   2011-03-14  NA       16
2   2011-03-15  NA       52
2   2011-11-22  24       NA
2   2011-12-12  NA       77
3   2009-03-02  NA       23
3   2009-05-02  15       NA
3   2011-12-02  NA       66
4   2017-07-03  NA       22", header = TRUE)
dt <- data.table(df)
dt[, TestDT := as.Date(TestDT)]
test1 <- dt[!is.na(Test1), .(ID, TestDT, Test1)]
test2 <- dt[!is.na(Test2), .(ID, TestDT, Test2)]
test1[, start.date := TestDT - 91]
test1[, end.date := TestDT + 91]
test2[, start.date := TestDT]
test2[, end.date := TestDT]
setkey(test2, ID, start.date, end.date)
res <- foverlaps(
test1, 
test2, 
by.x = c("ID", "start.date", "end.date"),
by.y = c("ID", "start.date", "end.date")
)

最新更新