I have data like the example below. For each participant, if a particular string ("trial_end") is present in the my_strings column I would like to remove all the rows after its appearance.
library(dplyr)
library(stringr)
library(tibble)
df1 <- tibble::tribble(
~participant_id, ~timestamp, ~my_strings,
1L, 1L, "other_string",
1L, 2L, "other_string",
1L, 3L, "trial_end",
1L, 4L, "other_string",
2L, 1L, "other_string",
2L, 2L, "other_string",
2L, 3L, "other_string",
2L, 4L, "other_string",
3L, 1L, "other_string",
3L, 2L, "trial_end",
3L, 3L, "other_string",
3L, 4L, "other_string"
)
My first attempt was to use str_detect to look for the presence of the string, which to provide the row number, then use filter to keep only that row and all those before it:
df2 <- df1 %>%
group_by(participant_id) %>%
filter(row_number() < (which(str_detect(my_strings, "trial_end"))) + 1)
This seems to throw an error when the string is not detected (e.g. participant 2 in the example here).
My next attempt was to add a conditional if_else, trying to effectively say 'IF the target string is detected THEN remove all the rows after for that participant, ELSE if the string is not detected, do nothing'.
df3 <- df1 %>%
group_by(participant_id) %>%
if_else(str_detect(my_strings, "trial_end"),
filter(row_number() < (which(str_detect(my_strings, "trial_end"))) + 1),
filter(timestamp < max(timestamp)))
This also returned an error:
Error: condition must be a logical vector, not a grouped_df/tbl_df/tbl/data.frame object.
My final attempt tried to make use of another answer already here, by placing the conditional if else inside filter, but this too produced an error.
df4 <- df1 %>%
group_by(participant_id) %>%
filter(if(str_detect(my_strings, "trial_end") < (which(str_detect(my_strings, "trial_end")) + 1))
else < n())
Can anyone point out the best approach for this problem? Is filter the wrong way to go about it?
Many thanks.
For clarity, the desired outcome would look like this:
desired_output <- tibble::tribble(
~participant_id, ~timestamp, ~my_strings,
1L, 1L, "other_string",
1L, 2L, "other_string",
1L, 3L, "trial_end",
2L, 1L, "other_string",
2L, 2L, "other_string",
2L, 3L, "other_string",
2L, 4L, "other_string",
3L, 1L, "other_string",
3L, 2L, "trial_end"
)