简体   繁体   中英

R function for multiple column based condition in dplyr

i HAVE A SET OF PATENT IDS with Record date and Disease status i want to drop the rows after 1 status occurrence of disease and retain the minimum record date of patient never diseased(ie disease=0 in all rows for the patient id). My data set look like

ID    Date    Disease
123 02-03-2012  0
123 03-03-2013  1
123 04-03-2014  0
321 03-03-2015  1
423 06-06-2016  1
423 07-06-2017  1
543 08-05-2018  1
543 09-06-2019  0
645 08-09-2019  0
645 10-10-2018  0
645 11-10 -2012 0 

and the output i want

ID     Date       Disease
123  02-03-2012    0
123  03-03-2013    1
321  03-03-2015    1
423  06-06-2016    1
543  08-05-2018    1
645  11-10 -2012   0

We can convert Dates , group_by ID and select rows till 1'st occurrence of 1 or the minimum value.

library(dplyr)

df %>%
  mutate(Date = as.Date(Date, "%d-%m-%Y")) %>%
  arrange(ID, Date) %>%
  group_by(ID) %>%
  filter(row_number() <= which.max(Disease == 1))

#     ID Date       Disease
#  <int> <date>       <int>
#1   123 2012-03-02       0
#2   123 2013-03-03       1
#3   321 2015-03-03       1
#4   423 2016-06-06       1
#5   543 2018-05-08       1
#6   645 2012-10-11       0

We can also use slice

library(dplyr)
library(lubridate)
df1 %>% 
   arrange(ID, dmy(Date)) %>%
   group_by(ID) %>%
   slice(seq_len(which.max(Disease)))
# A tibble: 6 x 3
# Groups:   ID [5]
#     ID Date       Disease
#  <int> <chr>        <int>
#1   123 02-03-2012       0
#2   123 03-03-2013       1
#3   321 03-03-2015       1
#4   423 06-06-2016       1
#5   543 08-05-2018       1
#6   645 11-10-2012       0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM