To show another alternative, because I like the simplicity of its syntax, you can use data.table too. Assuming your data.frame is called "df":
library(data.table) # data.table 1.8.7 For help type: help("data.table") DT <- data.table(df, key = "SUBJID") DT[, list(VISIT = max(VISIT)), by = key(DT)] # SUBJID V1 # 1: 40161 9 # 2: 40201 3 # 3: 40202 8 # 4: 40241 4
And, although we share many ways to do this in R, if you are comfortable with the SQL syntax, you can also use sqldf as follows:
library(sqldf) sqldf("select SUBJID, max(VISIT) `VISIT` from df group by SUBJID") SUBJID VISIT 1 40161 9 2 40201 3 3 40202 8 4 40241 4
source share