I have two dataframes: df1 and df2 (see example below). df1 contains a numeric start and end value per character id. df2 contains multiple events per character id, including a numeric time value.
library(dplyr)
df1 <- data_frame(id = c("A", "B"),
start = c(2, 3),
end = c(5, 9))
df2 <- data_frame(id = c(rep("A", 4), rep("B", 4)),
time = c(1, 3, 5, 8, 2, 3, 4, 10),
keep = c(FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, FALSE))
I am trying to filter events in df2 using dplyr based on the time value being equal to or in between the start and end values per id in df1. So the filter is "df2$time >= df1$start & df2$time <= df1$end" which should be executed for each id separatly. I've added a logical column "keep" to show which rows I want to keep in df2.
How can I execute this filter for each id? Preferably using dplyr. This should be the endresult:
df2 %>%
filter(keep == TRUE)
Any help is much appreciated!