首页 > 解决方案 > 在回顾之前的行时创建一个新变量

问题描述

我有一个简单的患者就诊数据集:

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

所以最终的数据集看起来像这样:

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"))

标签: rdatetimelagdplyr

解决方案


您可以尝试使用以下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>

推荐阅读