r - 条件匹配时滞后于 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()
检查条件这样的功能,还是我应该完全做其他事情?
解决方案
我会建议这样的东西。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 创建
推荐阅读
- amazon-web-services - Terraform - volume_tags 和新附加的 EBS
- mongodb - heroku mongo typeerror 无法读取 null 的属性“拆分”
- flutter - 文件未从 DocumentDirectory Path Flutter 加载
- docker - 在 docker-compose 中结合 Next.JS 和 json-server
- r - 检测 df1 中的列与 df2 中的列的部分匹配,并在 R 中输出匹配的值
- java - 移除后未移除 LiveData 观察者
- php - 从可变数量的 HTML 复选框插入 SQL
- c# - 循环遍历彩色复选框
- azure - 我在 Linux 上的 Azure Web 应用程序不工作。azure 日志上的错误消息“react-scripts: not found”和 github “npm ERR!code ELIFECYCLE”
- arrays - 大家好,我正在处理 C++ 中的一个简单交换问题(两个字符串)。我无法让我的交换工作。我的输出只是“精彩的一天”