I have a large time-series dataset of patients with different diagnoses. A snapshot of the dataset is below:
time<-rep(1:3, times = 5)
ID<-c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5)
Dx1<-c("CBS", "CBS", "CBS", "OtherDx", "OtherDx", "OtherDx", "ACC", "ACC", "ACC", "OtherDx", "OtherDx", "CBS", "OtherDx", "OtherDx", "OtherDx")
Dx2<-c("OtherDx", "OtherDx", "OtherDx", "OtherDx", "OtherDx", "OtherDx", "CBS", "CBS", "CBS", "OtherDx","OtherDx", "OtherDx", "OtherDx","OtherDx", "OtherDx")
df<-tibble(time, ID, Dx1, Dx2)
# A tibble: 15 x 4
ID time Dx1 Dx2
<dbl> <int> <chr> <chr>
1 1 1 CBS OtherDx
2 1 2 CBS OtherDx
3 1 3 CBS OtherDx
4 2 1 OtherDx OtherDx
5 2 2 OtherDx OtherDx
6 2 3 OtherDx OtherDx
7 3 1 ACC CBS
8 3 2 ACC CBS
9 3 3 ACC CBS
10 4 1 OtherDx OtherDx
11 4 2 OtherDx OtherDx
12 4 3 CBS OtherDx
13 5 1 OtherDx OtherDx
14 5 2 OtherDx OtherDx
15 5 3 OtherDx OtherDx
Here, I want to filter and keep only those IDs that have "OtherDx" in both Dx1 and Dx2 for all three time observations. In this snapshot, that would mean keeping only IDs 2 and 5 (not ID 4 as there is a non "OtherDx" value at Time 3).
My dplyr code is:
df2 <- df %>%
group_by(ID, time) %>%
filter(
time== c(1:3) & Dx1== "OtherDx" & Dx2== "OtherDx"
)
But my code doesn't seem to do the job and includes ID 4 as well. What is the best way to extract this data?