Remove entire IDs from the dataframe based on multiple conditions

Viewed 77

I want to remove the entire ids from the patient data set with multiple condition in which the record date equal to fvdate should be removed completely. my data set will look like

ID  Record date Disease  Fvdate
1   02-03-2012   0     02-03-2012
2   03-03-2013   1     03-03-2013
3   04-03-2014   0     04-03-2014
3   03-03-2015   1     03-03-2015
4   06-06-2016   1     02-03-2012
4   07-06-2017   1     03-03-2013
5   08-05-2018   1     04-03-2014
6   09-06-2019   0     03-03-2015

i want the output to be

ID  Record date Disease  Fvdate
1   02-03-2012   0    02-03-2012
2   03-03-2013   1    03-03-2013
4   06-06-2016   1    02-03-2012
4   07-06-2017   1    03-03-2013
5   08-05-2018   1    04-03-2014
6   09-06-2019   0    03-03-2015

Example input data:

d <- read.table(text = "
ID  Record_date Disease  Fvdate
1   02-03-2012   0     02-03-2012
2   03-03-2013   1     03-03-2013
3   04-03-2014   0     04-03-2014
3   03-03-2015   1     03-03-2015
4   06-06-2016   1     02-03-2012
4   07-06-2017   1     03-03-2013
5   08-05-2018   1     04-03-2014
6   09-06-2019   0     03-03-2015", header = TRUE, stringsAsFactors = FALSE)
1 Answers

Filter on condition that dates are not the same OR number of rows per ID is 1:

library(dplyr)

d %>% 
  group_by(ID) %>% 
  filter(!Record_date == Fvdate | n() == 1)

#   ID Record_date Disease     Fvdate
# 1  1  02-03-2012       0 02-03-2012
# 2  2  03-03-2013       1 03-03-2013
# 3  4  06-06-2016       1 02-03-2012
# 4  4  07-06-2017       1 03-03-2013
# 5  5  08-05-2018       1 04-03-2014
# 6  6  09-06-2019       0 03-03-2015
Related