I have panel data (subject/year) for which I would like to only keep subjects who appear the maximum number of times per year. The data set is large so I am using the data.table package. Is there a more elegant solution than what I have tried below?
library(data.table)
DT <- data.table(SUBJECT=c(rep('John',3), rep('Paul',2),
rep('George',3), rep('Ringo',2),
rep('John',2), rep('Paul',4),
rep('George',2), rep('Ringo',4)),
YEAR=c(rep(2011,10), rep(2012,12)),
HEIGHT=rnorm(22),
WEIGHT=rnorm(22))
DT
DT[, COUNT := .N, by='SUBJECT,YEAR']
DT[, MAXCOUNT := max(COUNT), by='YEAR']
DT <- DT[COUNT==MAXCOUNT]
DT <- DT[, c('COUNT','MAXCOUNT') := NULL]
DT
data.tablehad some of the samebycapabilities in theiexpression as it does injexpressions. - Señor O