'Subset cases in which there were more than 3 observations in longitudinal data?

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.



Solution 1:[1]

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)
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dion Groothof