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 :

Method 1

# set as data table
setDT(df)

# calculate no. of waves per ID
df[, no_of_waves := .N, ID]

# subset
df[no_of_waves >= 3]

Method 2

# calculate no. of waves per ID
df[, no_of_waves := max(Wave), ID]

# subset
df[no_of_waves >= 3]

Leave a Reply