我有一个简单的患者就诊数据集:
date infection
2005-01-01 yes
2005-06-30 yes
2005-10-15 yes
2006-01-01 no
2006-06-01 no
2006-11-01 yes
2006-12-01 no
2007-11-15 yes
在R,我想添加一个名为列chronic
,其取值yes
,no
,NA
。
yes
仅在当前日期感染=='是'并且在过去365天中有两个感染=='是'行时才显示该值。NA
在过去365天中没有两次访问no
因此,最终数据集将如下所示:
date infection chronic
2005-01-01 yes NA
2005-06-30 yes NA
2005-10-15 yes yes
2006-01-01 no no
2006-06-01 no no
2006-11-01 yes no
2006-12-01 no no
2007-11-15 yes NA
我该如何编码?理想情况下dplyr
,我想使用,但是我愿意接受任何解决方案。谢谢!
可以使用以下代码重新创建数据集:
dat <- data.frame(date = c(as.Date("2005-01-01"), as.Date("2005-06-30"), as.Date("2005-10-15"), as.Date("2006-01-01"), as.Date("2006-06-01"), as.Date("2006-11-01"), as.Date("2006-12-01"), as.Date("2007-11-15")), infection = c("yes", "yes", "yes", "no", "no", "yes", "no", "yes"))
您可以尝试使用以下map
功能purrr
:
library(dplyr)
library(purrr)
dat %>%
mutate(chronic = map2_chr(date, infection,
~case_when(.y == 'yes' &
sum(infection[between(date, .x-365, .x - 1)] == 'yes') >= 2 ~ 'yes',
.y == 'yes' &
sum(infection[between(date, .x-365, .x - 1)] == 'yes') != 2 ~ NA_character_,
TRUE ~ 'no')))
# date infection chronic
#1 2005-01-01 yes <NA>
#2 2005-06-30 yes <NA>
#3 2005-10-15 yes yes
#4 2006-01-01 no no
#5 2006-06-01 no no
#6 2006-11-01 yes <NA>
#7 2006-12-01 no no
#8 2007-11-15 yes <NA>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句