Minimal example - I have 9 responses from 3 subjects to a questionnaire with two questions:
set.seed(1)
df <- data.frame(ID = c(rep("A", 2), rep("B", 3), rep("C", 4)),
Q1 = sample(0:5, 9, replace=T),
Q2 = sample(1:7, 9, replace=T),
Days_Used = c(rep(10, 2), rep(5, 3), rep(4, 4))
)
Think of Days_Used as End_Date - Start_Date. I would like to filter the dataframe in one of two ways - by Days_Used or the number of times the questionnaire is filled (i.e. by the number of rows associated with a subject), depending on whether the variable FILTER_BY_DAYS_USED is TRUE or FALSE. I tried the following:
FILTER_BY_DAYS_USED <- TRUE
df %>%
group_by(ID) %>%
if_else(FILTER_BY_DAYS_USED,
filter(Days_Used >= 5),
filter(n() >= 3))
but get an error message when I execute it
Error: `condition` must be a logical vector, not a grouped_df/tbl_df/tbl/data.frame` object.
I would like to obtain the following output:
When
FILTER_BY_DAYS_USEDisTRUE: the first 5 rows corresponding to subjects A and BWhen
FILTER_BY_DAYS_USEDisFALSE: the last 7 rows corresponding to subjects B and C
What is the correct syntax for my conditional filter?
Many thanks in advance
Thomas Philips