代码之家  ›  专栏  ›  技术社区  ›  tushaR

在R[duplicate]中的data.table中创建序列

  •  1
  • tushaR  · 技术社区  · 8 年前

    dt=data.table(id=c(1,1,1,1,1,2,2,2,3,3,3),
     lob=c("A","A","B","B","C","A","B","C","A","A","B"),
     month=c(11,11,12,1,1,11,12,12,11,12,1))
    

    逻辑如下:对于给定的 身份证件 高球

    例如:

    如果对于一个ID,在给定的一个月内存在a、a、B、C…优先级应为1、1、2、3

    如果对于一个ID,在一个给定的月份中存在B,B,C…优先级应该是1,1,2

    我希望第四列中有一个基于id、lob和month的序列,如下所示:

    id lob month priority
     1   A    11        1
     1   A    11        1
     1   B    12        1
     1   B     1        1
     1   C     1        2
     2   A    11        1
     2   B    12        1
     2   C    12        2
     3   A    11        1
     3   A    12        1
     3   B     1        1
    
    1 回复  |  直到 8 年前
        1
  •  4
  •   Ronak Shah    8 年前

    我们可以用 match 具有 unique lob

    library(data.table)
    dt[, priority := match(lob, unique(lob)), by = .(id, month)]
    
    dt
    #    id lob month priority
    # 1:  1   A    11        1
    # 2:  1   A    11        1
    # 3:  1   B    12        1
    # 4:  1   B     1        1
    # 5:  1   C     1        2
    # 6:  2   A    11        1
    # 7:  2   B    12        1
    # 8:  2   C    12        2
    # 9:  3   A    11        1
    #10:  3   A    12        1
    #11:  3   B     1        1
    

    使用相同的逻辑 dplyr 版本

    library(dplyr)
    dt %>%
      group_by(id, month) %>%
      mutate(pr = match(lob, unique(lob)))
    

    基本R版本使用 ave

    dt$priority <- with(dt, ave(lob, id, month, FUN = function(x) match(x, unique(x))))
    
    推荐文章