Compare to next row, grouped, data.table

后端 未结 2 1176
梦谈多话
梦谈多话 2021-01-21 23:51

I have a data frame containing number of page views per user, per week. I want to determine, for each user, whether their views increased, decreased, or stayed the same after a

相关标签:
2条回答
  • 2021-01-22 00:20

    Since version v1.9.6 (on CRAN 19 Sep 2015), the shift() function is available in data.table:

    DT[, difference := shift(numviews, type = "lead") - numviews, by = Userid][
      xeventinweek != 0L]
    
       Userid week xeventinweek numviews difference
    1:  Alice    1            2        5         -2
    2:  Alice    4            1        6         NA
    3:    Bob    2            2        3          2
    
    0 讨论(0)
  • 2021-01-22 00:38

    Using match:

    dat[, numnextweek := numviews[match(week + 1, week)] , by=Userid]
    dat[, difference := numviews - numnextweek , by=Userid]
    dat[xeventinweek != 0]
    
    #   Userid week xeventinweek numviews numnextweek difference
    #1:  Alice    1            2        5           3          2
    #2:  Alice    4            1        6          NA         NA
    #3:    Bob    2            2        3           5         -2
    
    0 讨论(0)
提交回复
热议问题