I am looking to extract the second occurrence of a subject ID (the entire row of their data) OR the first if the row is not repeated.
These data are from repeated visits and we are interested in only subjects from last-non-missing data, meaning that either the subject has "screening" information and no "injection" or they have both. This is how we define "baseline." If subject has both, we only want to retain the row of data with the injection (last data before treatment), if only screening then screening (that's then the last data before treatment and will equal baseline).
Here's some data:
df1 <- data.frame(ID = c(1, 2, 2, 3, 3, 4),
visit = c('screening', 'screening', 'injection', 'screening',
'injection', 'screening'),
var2 = c(1, 6, 3, 12, 0, 2))
What I have attempted:
- Separating out and re-merging data frames that contain the two qualifiers for these subjects. But when I do so, the columns just get duplicated, producing a wide instead of long dataset (when they obviously match by the exact same ID).
- Using a filter in dplyr with multiple conditions, but it only catches those with screening because that always comes first for the repeated subjects.
Suggestions?