仅当Med 0出现在Med = 1日期之前的某个日期,我才想过滤所有Med = 0(按ID分组)。如何使用dplyr,base r或其他软件包来完成此操作。
df <- read.table(header = TRUE, text = "
ID Med date
1 0 2006-01-01
1 0 2006-02-02
1 1 2006-06-02
1 0 2006-08-02
1 2 2007-12-01
2 0 2003-01-01
2 1 2003-02-02
2 3 2003-06-02
2 0 2003-08-02
2 8 2007-12-01
3 1 2007-04-20
",stringsAsFactors=FALSE)
答案 0 :(得分:1)
使用dplyr
,您可以group_by
ID
arrange
,date
并选择Med == 1
之前的行
library(dplyr)
df %>%
group_by(ID) %>%
arrange(date) %>%
filter(cumsum(Med == 1) == 0 & Med == 0)
# ID Med date
# <int> <int> <chr>
#1 1 0 2006-01-01
#2 1 0 2006-02-02
#3 2 0 2003-01-01