【问题标题】:How to compare dates and create a new categorical variable? [duplicate]如何比较日期并创建新的分类变量? [复制]
【发布时间】:2023-04-02 14:00:01
【问题描述】:
newdf=data.frame(id=c(1,3,1,2,1,3,2,2),
                 dates=c("2020-05-19","2020-05-02","2020-05-20","2020-05-09","2020-05-21","2020-05-04","2020-05-10","2020-05-11"),
                 antibiotic=c("Yes","No","Yes","Yes","Yes","No","Yes","Yes"),
                 culture=c("2020-05-15","","","","","","2020-05-11","2020-05-12"),
                 culture1=c("","","","","","","2020-05-08",""))

newdf$dates=as.Date(newdf$dates)
newdf$culture=as.Date(newdf$culture)
newdf$culture1=as.Date(newdf$culture1)
newdf=newdf[order(newdf$dates),]

#I think this doesn't work well
testdata=newdf %>% group_by(id) %>%
  mutate(culture_sent = case_when((dates >= min(culture,culture1,na.rm = T)) & (antibiotic == 'Yes') ~ 'Yes', TRUE ~ 'No'))

我想创建新的分类变量('Yes','No')调用'culture_sent'。如果最小培养日期和培养 1 小于日期(日期变量)和抗生素“是”,那么我想为该特定患者输入“是”(否则为“否”)。我尝试了一种方法,但我相信,它并没有给出我想要的答案。您能否建议一种方法来做到这一点?我附上了数据集的图片。

【问题讨论】:

    标签: r date dplyr


    【解决方案1】:

    你可以试试if_else -

    library(dplyr)
    
    newdf %>%
      mutate(culture_sent = if_else(dates > pmin(culture, culture1, na.rm = TRUE) & 
                                antibiotic == 'Yes', 'Yes', 'No', missing = 'No'))
    
    #  id      dates antibiotic    culture   culture1 culture_sent
    #2  3 2020-05-02         No       <NA>       <NA>           No
    #6  3 2020-05-04         No       <NA>       <NA>           No
    #4  2 2020-05-09        Yes       <NA>       <NA>           No
    #7  2 2020-05-10        Yes 2020-05-11 2020-05-08          Yes
    #8  2 2020-05-11        Yes 2020-05-12       <NA>           No
    #1  1 2020-05-19        Yes 2020-05-15       <NA>          Yes
    #3  1 2020-05-20        Yes       <NA>       <NA>           No
    #5  1 2020-05-21        Yes       <NA>       <NA>           No
    

    pmin(culture, culture1, na.rm = TRUE) 将为您提供cultureculture1 之间的最短日期。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-26
      • 2021-12-09
      • 1970-01-01
      • 2015-03-08
      • 2016-01-13
      • 2019-07-03
      • 2013-05-30
      • 1970-01-01
      相关资源
      最近更新 更多