Add a “rank” column to a data frame

前端 未结 5 1838
滥情空心
滥情空心 2020-11-27 14:43

I have a dataframe with counts of different items, in different years:

df <- data.frame(item = rep(c(\'a\',\'b\',\'c\'), 3),
                 year = rep(c         


        
相关标签:
5条回答
  • 2020-11-27 15:01

    Using order function,

    transform(dat, x= ave(count,year,FUN=function(x) order(x,decreasing=T)))
      item year count x
    1    a 2010     1 3
    2    b 2010     4 2
    3    c 2010     6 1
    4    a 2011     3 2
    5    b 2011     8 1
    6    c 2011     3 3
    7    a 2012     5 3
    8    b 2012     7 2
    9    c 2012     9 1
    

    EDIT

    You can use plyr here also:

    ddply(dat,.(year),transform,x =  order(count,decreasing=T))
    
    0 讨论(0)
  • 2020-11-27 15:05

    While using the answers given by others, I found that the following performs faster than the transform and dyplr variants:

    df$year.rank <- ave(count, year, FUN = function(x) rank(-x, ties.method = "first"))
    
    0 讨论(0)
  • 2020-11-27 15:06

    Using dplyr you could do it as follows:

    library(dplyr) # 0.4.1
    df %>% 
      group_by(year) %>% 
      mutate(yrrank = row_number(-count))
    
    #Source: local data frame [9 x 4]
    #Groups: year
    #
    #  item year count yrrank
    #1    a 2010     1      3
    #2    b 2010     4      2
    #3    c 2010     6      1
    #4    a 2011     3      2
    #5    b 2011     8      1
    #6    c 2011     3      3
    #7    a 2012     5      3
    #8    b 2012     7      2
    #9    c 2012     9      1
    

    It is the same as:

    df %>% 
      group_by(year) %>% 
      mutate(yrrank = rank(-count, ties.method = "first"))
    

    Note that the resulting data is still grouped by "year". If you want to remove the grouping you can simply extend the pipe with %>% ungroup().

    0 讨论(0)
  • 2020-11-27 15:13

    There is a rank function to help you with that:

    transform(df, 
              year.rank = ave(count, year, 
                              FUN = function(x) rank(-x, ties.method = "first")))
      item year count year.rank
    1    a 2010     1         3
    2    b 2010     4         2
    3    c 2010     6         1
    4    a 2011     3         2
    5    b 2011     8         1
    6    c 2011     3         3
    7    a 2012     5         3
    8    b 2012     7         2
    9    c 2012     9         1
    
    0 讨论(0)
  • 2020-11-27 15:27

    data.table version for practice:

    library(data.table)
    DT <- as.data.table(df)
    DT[,yrrank:=rank(-count,ties.method="first"),by=year]
    
       item year count yrrank
    1:    a 2010     1      3
    2:    b 2010     4      2
    3:    c 2010     6      1
    4:    a 2011     3      2
    5:    b 2011     8      1
    6:    c 2011     3      3
    7:    a 2012     5      3
    8:    b 2012     7      2
    9:    c 2012     9      1
    
    0 讨论(0)
提交回复
热议问题