In R, how to sum certain rows of a data frame with certain logic?

前端 未结 5 1811
情书的邮戳
情书的邮戳 2021-01-06 17:33

Hi experienced R users,

It\'s kind of a simple thing. I want to sum x by Group.1 depending on one controllable variable.

I\'d like

5条回答
  •  梦毁少年i
    2021-01-06 18:11

    If the sums you want are always cumulative, there's a function for that, cumsum. It works like this.

    > cumsum(c(1,2,3))
    [1] 1 3 6
    

    In this case you might want something like

    > mysum <- cumsum(yourdata$x)
    > mysum[2] # the sum of the first two rows
    > mysum[3] # the sum of the first three rows
    > mysum[number] # the sum of the first "number" rows
    

提交回复
热议问题