Cumulative sum by group in sqldf?

前端 未结 3 817
余生分开走
余生分开走 2020-12-19 23:51

I have a data frame with 3 variables: place, time, and value (P, T, X). I want to create a fourth variable which will be the cumulative sum of X. Normally I like to do group

3条回答
  •  感情败类
    2020-12-20 00:21

    Or, another option is data.table.

    > library(data.table)
    > DT = data.table(place = 1:4, time = rep(1:3, each = 4), value = 1:3)
    > setkey(DT,place,time)   # order by place and time
    > DT
          place time value
     [1,]     1    1     1
     [2,]     1    2     2
     [3,]     1    3     3
     [4,]     2    1     2
     [5,]     2    2     3
     [6,]     2    3     1
     [7,]     3    1     3
     [8,]     3    2     1
     [9,]     3    3     2
    [10,]     4    1     1
    [11,]     4    2     2
    [12,]     4    3     3
    > DT[,list(time,value,cumsum(value)),by=place]
          place time value V3
     [1,]     1    1     1  1
     [2,]     1    2     2  3
     [3,]     1    3     3  6
     [4,]     2    1     2  2
     [5,]     2    2     3  5
     [6,]     2    3     1  6
     [7,]     3    1     3  3
     [8,]     3    2     1  4
     [9,]     3    3     2  6
    [10,]     4    1     1  1
    [11,]     4    2     2  3
    [12,]     4    3     3  6
    > 
    

提交回复
热议问题