尽管(据说)关系相当密切,但还是找不出答案。我想看看有没有在4小时内给药。
drug start stop
1 A 1 3
2 A 7 10
3 A 11 17药物A开始于第1次,给药至第3次,然后在第7次再次开始,直至第10次放弃等。
t1 t2
1 0 4
2 4 8
3 8 12
4 12 16
5 16 20
6 20 24这些都是有问题的窗户
数据:
t1 <- c(0,4,8,12,16,20)
t2 <- t1 + 4
chunks <- data.frame(t1=t1,t2=t2)
drug <- "A"
start <- c(1,7,11)
stop <- c(3,10,17)
times <- data.frame(drug,start,stop)期望解
t1 t2 lsg
1 0 4 1
2 4 8 1
3 8 12 1
4 12 16 1
5 16 20 1
6 20 24 0对解决的尝试
test <- function(){
n <- 1
for (row in times){
result <- (times$start[n] > chunks$t1 & times$stop[n] < chunks$t2) | ((times$start[n] > chunks$t1 & times$start[n] < chunks$t2) & (times$stop[n] > chunks$t2 | times$stop[n] < chunks$t2)) | (times$start[n] < chunks$t1 & times$stop[n] > chunks$t1)
n <- n + 1
print(result)
}
}给出
[1] TRUE FALSE FALSE FALSE FALSE FALSE
[1] FALSE TRUE TRUE FALSE FALSE FALSE
[1] FALSE FALSE TRUE TRUE TRUE FALSE这是正确的!第一届政府进入了第一时间窗口。第二和第三次给药进入第二和第三窗口等,但如何达到预期的解决方案?
就像我说的,我感觉很亲密,但我不知道如何把结果加入到块中去-df.
发布于 2020-05-27 22:33:01
其中的前半部分是@akrun的评论,但扩展到包含了先决条件。(如果你回来接电话,我很乐意听你的话.只是在这里提供更多的细节。)下半场是新的(而且经常看得过头)。
data.table
data.table::foverlaps确实是基于重叠/不等式(而不是基merge和dplyr::*_join,后者只在严格的等式上操作)连接的。使用overlaps (除了是data.table类之外)的一个先决条件是正确地编辑时间字段。
library(data.table)
setDT(times)
setDT(chunks)
# set the keys
setkey(times, start, stop)
setkey(chunks, t1, t2)
# the join
+(!is.na(foverlaps(chunks, times, which = TRUE, mult = 'first')))
# [1] 1 1 1 1 1 0函数实际上返回times中的每一行对应于chunks中的行。
foverlaps(chunks, times, which = TRUE, mult = 'first')
# [1] 1 2 2 3 3 NA平方
data.table并不是唯一允许这种情况发生的R工具。此解决方案适用于data.frame的任何变体(base、data.table或tbl_df)。
这里是这样的:
library(sqldf)
sqldf("
select c.t1, c.t2,
(case when drug is null then 0 else 1 end) > 0 as n
from chunks c
left join times t on
(t.start between c.t1 and c.t2) or (t.stop between c.t1 and c.t2)
or (c.t1 between t.start and t.stop) or (c.t2 between t.start and t.stop)
group by c.t1, c.t2")
# t1 t2 n
# 1 0 4 1
# 2 4 8 1
# 3 8 12 1
# 4 12 16 1
# 5 16 20 1
# 6 20 24 0(我不知道是否有可能减少连接的逻辑,也不知道它是否会错误地处理其他数据。)
如果你需要在每个时间框架内的药物计数,我认为你可以使用sum(case when ... end) as n。
https://stackoverflow.com/questions/62053582
复制相似问题