r - 在回顾之前的行时创建一个新变量
问题描述
我有一个简单的患者就诊数据集:
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
仅当当前日期的感染=='yes' 并且在前 365 天内有两个感染=='yes' 行时,它才会显示该值。- 否则,
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>
推荐阅读
- r - 如何为输出文件着色
- android - 当我将滚动视图添加为线性布局的父级时,回收器视图不可见,其中回收器视图与框架布局和滑动刷新布局一起放置
- visual-studio-code - 你如何在 vscode 编辑器中缩小 favicon.ico?
- javascript - 在 WebBluetooth 开发中,我如何知道设备 BLE 外围设备提供的服务和特性的 UUID?
- go - “go test”和“bazel test”中的不同文件权限错误
- c# - 使用“new()”的方法比不使用“new()”的方法和 C# 中的方法中的 where 子句有什么好处?
- django-rest-framework - 如何在 django rest api 中序列化 ckeditor“richtextfield”?
- python - 如何将第二个 csv 的未重复行添加到第一个的末尾并合并到新的 csv?
- react-native - 无法让相机使用 expoTHREE 和 expoGRAPHICS 在 React-native 项目中创建 AR 场景
- machine-learning - 在语言建模中,为什么我必须在每个新的训练时期之前初始化隐藏权重?(火炬)