首页 > 解决方案 > 条件匹配时滞后于 R

问题描述

我有一个数据框,其中只有体检日期和是否存在感染(是/否),我想添加第三列代表最后一次感染的日期。如果患者以前没有感染过,则新last_infection列应该有。NA如果他们以前曾感染过,则应显示他们最近一次就诊的日期,他们测试“是”感染。

我希望输出看起来像这样:

date      infection   last_infection
01-01-18  no          NA
06-01-18  no          NA
07-01-18  yes         NA
09-01-18  no          07-01-18
01-01-19  no          07-01-18
02-01-19  yes         07-01-18
03-01-19  yes         02-01-19
04-01-19  no          03-01-19
05-01-19  no          03-01-19

我怎样才能在 R 中做到这一点?可以像lag()检查条件这样的功能,还是我应该完全做其他事情?

标签: rfunctionlag

解决方案


我会建议这样的东西。fill如果您从 tidyr 包中使用,则没有理由使用 cumsum 或分组。

library(tidyverse)

df %>% 
  mutate(
    last_infection = if_else(lag(infection) == "yes", lag(date), NA_character_)
  ) %>% 
  fill(last_infection)
#> # A tibble: 9 x 3
#>   date     infection last_infection
#>   <chr>    <chr>     <chr>         
#> 1 01-01-18 no        <NA>          
#> 2 06-01-18 no        <NA>          
#> 3 07-01-18 yes       <NA>          
#> 4 09-01-18 no        07-01-18      
#> 5 01-01-19 no        07-01-18      
#> 6 02-01-19 yes       07-01-18      
#> 7 03-01-19 yes       02-01-19      
#> 8 04-01-19 no        03-01-19      
#> 9 05-01-19 no        03-01-19

reprex 包(v0.3.0)于 2020-01-25 创建


推荐阅读