r - 如果在 R 中满足两个条件,则删除所有 id
问题描述
我有一组带有记录日期和首次就诊日期以及疾病状态的患者 ID ,如果他们具有相同的记录日期和首次就诊日期,我想删除所有患者 ID。我的数据集看起来像
p_id Record_date fvdate Disease
12 02-03-2017 02-03-2017 1
12 05-03-2017 02-03-2017 0
12 03-04-2018 02-03-2017 1
11 04-05-2016 05-06-2017 0
13 18-06-2017 18-06-2017 1
13 03-05-2018 18-06-2017 0
13 09-09-2019 18-06-2017 0
14 09-12-2017 03-01-2018 1
我需要的输出
p_id Record_date fvdate Disease
11 04-05-2016 05-06-2017 0
14 09-12-2017 03-01-2018 1
先感谢您
解决方案
我们可以选择与那first
Record_date
不同的组。fvdate
p_id
library(dplyr)
df %>% group_by(p_id) %>% filter(first(Record_date) != first(fvdate))
# p_id Record_date fvdate Disease
# <int> <fct> <fct> <int>
#1 11 04-05-2016 05-06-2017 0
#2 14 09-12-2017 03-01-2018 1
或者 :
df %>% group_by(p_id) %>% filter(!any(Record_date == first(fvdate)))
数据
df <- structure(list(p_id = c(12L, 12L, 12L, 11L, 13L, 13L, 13L, 14L
), Record_date = c("02-03-2017", "05-03-2017", "03-04-2018",
"04-05-2016", "18-06-2017", "03-05-2018", "09-09-2019", "09-12-2017"
), fvdate = c("02-03-2017", "02-03-2017", "02-03-2017", "05-06-2017",
"18-06-2017", "18-06-2017", "18-06-2017", "03-01-2018"), Disease = c(1L,
0L, 1L, 0L, 1L, 0L, 0L, 1L)), row.names = c(NA, -8L), class = "data.frame")
推荐阅读
- python - 在排序一个列表期间将不同列表中的相关元素保持在一起
- c# - 如何对通用列表对象进行排序
- javascript - 向和从 js 服务器发送数据的基本方法?
- json - 使用 Pyspark 处理 JSON 结构
- amazon-web-services - 为什么角色假设应该在 lambda 内部完成?
- html - 如何将数值绑定到 CSS 以创建时间线?
- docker - 如何为 docker compose 环境变量设置运行时变量
- javascript - 仅在 Javascript 中具有不同段落的动态 Div
- tsql - 表格模型中的测量列未在浏览器中显示正确的值
- javascript - 调用此函数时如何获取返回值?