select maximum row value by group

前端 未结 5 1108
醉梦人生
醉梦人生 2021-01-20 07:53

I\'ve been trying to do this with my data by looking at other posts, but I keep getting an error. My data new looks like this:

id  year    name          


        
5条回答
  •  不思量自难忘°
    2021-01-20 08:13

    You can do this with duplicated

    # your data
     df <- read.table(text="id  year    name    gdp
    1   1980    Jamie   45
    1   1981    Jamie   60
    1   1982    Jamie   70
    2   1990    Kate    40
    2   1991    Kate    25
    2   1992    Kate    67
    3   1994    Joe     35
    3   1995    Joe     78
    3   1996    Joe     90" , header=TRUE)
    
    # Sort by id and year (latest year is last for each id)
    df <- df[order(df$id , df$year), ]
    
    # Select the last row by id
    df <- df[!duplicated(df$id, fromLast=TRUE), ]
    

提交回复
热议问题