extract last row for each subject from a data frame

r

Solution

While agstudy is correct, there is another way with the stats package and the aggregate function.

df <- read.table(text="SUBJID VISIT
40161 3
40161 4
40161 5
40161 6
40161 9
40201 3
40202 6
40202 8
40241 3
40241 4", header=TRUE)


aggregate(VISIT ~ SUBJID, df, max)

  SUBJID VISIT
1  40161     9
2  40201     3
3  40202     8
4  40241     4

Problem

I have a data frame in R like this. I would like to extract the last visit for each subject. SUBJID VISIT ``` 40161 3 40161 4 40161 5 40161 6 40161 9 40201 3 40202 6 40202 8 40241 3 40241 4 ``` The desired output is as follows SUBJID VISIT ``` 40161 9 40201 3 40202 8 ``` How should I do this in R? Thanks very much for your help.

Original source