First observation by group using self-join

后端 未结 2 1767
情话喂你
情话喂你 2020-12-15 07:07

I\'m trying to get the top row by a group of three variables using a data.table.

I have a working solution:

col1 <- c(1,1,1,1,2,2,2,2,3,3,3,3)
col         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-15 07:27

    What about:

    solution2 <- data.table(data)[ , sales[1], by="store,year,month"]
    > solution2
       store year month V1
    1:     1 2000    12  1
    2:     1 2001    12  3
    3:     2 2000    12  5
    4:     2 2001    12  7
    5:     3 2000    12  9
    6:     3 2001    12 11
    

    I suppose you could rename that column:

    data.table(data)[,fsales := sales[1],by="store,year,month"]
    

提交回复
热议问题