Reputation: 3
Have a set of longitudinal data in which measures were repeatedly collected at various waves (see example of set up below. As this sort of data goes however, there was attrition, with some waves stopping before the study ended. However, my analysis has the assumption that each participant have at least 3 observations
ID | Wave | Score |
---|---|---|
1000 | 0 | 5 |
1000 | 1 | 4 |
1001 | 0 | 6 |
1001 | 1 | 6 |
1001 | 2 | 7 |
How would I subset only those IDs (subjects) that have at least 3 observations? I've looked into similar questions on stackoverflow but they do not seem to fit this specific issue.
Upvotes: 0
Views: 183
Reputation: 1456
Using base R, you could try this one-liner.
out <- with(df, df[ID %in% names(which(sapply(split(df, ID), nrow) > 2)), ])
Output
> out
ID Wave Score
3 1001 0 6
4 1001 1 6
5 1001 2 7
Data
df <- data.frame(
ID = unlist(mapply(rep, 1000:1001, 2:3)),
Wave = c(0,1,0,1,2),
Score = c(5,4,6,6,7)
)
Upvotes: 0
Reputation: 1873
# set as data table
setDT(df)
# calculate no. of waves per ID
df[, no_of_waves := .N, ID]
# subset
df[no_of_waves >= 3]
# calculate no. of waves per ID
df[, no_of_waves := max(Wave), ID]
# subset
df[no_of_waves >= 3]
Upvotes: 0