我有格式的数据
set.seed(40)
subject <- sample(c("mike", "john", "steve"), 20, replace = TRUE)
test1 <- sample(c("pos", "neg", "pos", "neg", "NA"), 20, replace = TRUE)
testdate <- Sys.Date() + sample(-1000:1000, 20, replace = FALSE)
mydf <- data.frame(subject, testdate, test1)
mydf$status <- "unknown"
对于每个主题,我想修改 status 的值,以便:a)在获得 test1 的最早(按测试日期)pos 或 neg 结果之前,它仍然是未知的;b) 当获得第一个 pos test1 结果时,该日期和之后的状态变为“in”,无论任何后续 test1 值如何;c) 如果 test1 在任何阳性结果之前出现阴性结果,则该日期和后续日期的状态变为“out”,直到获得任何阳性 test1 结果。对所有解决方案开放。我正在试验 dplyr,并且会对基于 dplyr 的解决方案特别感兴趣。
输出将是
subject testdate test1 status
john 2014-11-20 neg negative
john 2015-07-29 neg negative
john 2015-11-10 neg negative
john 2017-04-08 neg negative
john 2018-09-18 NA negative
mike 2014-09-01 pos positive
mike 2014-10-14 neg positive
mike 2015-03-22 neg positive
mike 2016-09-15 pos positive
mike 2017-08-18 neg positive
mike 2017-12-20 pos positive
mike 2018-09-06 NA positive
mike 2019-09-02 neg positive
steve 2015-06-21 neg negative
steve 2016-01-03 pos positive
steve 2016-03-12 neg positive
steve 2017-06-26 neg positive
steve 2017-12-02 neg positive
steve 2018-12-20 pos positive
steve 2019-06-20 pos positive