Apply a function to groups within a data.frame in R

前端 未结 4 1863
臣服心动
臣服心动 2020-12-14 20:51

I am trying to get the cumulative sum of a variable (v) for groups (\"a\" and \"b\") within a dataframe. How can I get the result at the bottom -- whose rows are even number

4条回答
  •  生来不讨喜
    2020-12-14 21:08

    I would use ave. If you look at the source of ave, you'll see it essentially wraps Martin Morgan's solution.

    R> g <- factor(c("a","b","a","b","a","b","a","b","a","b","a","b"))
    R> v <- c(1,4,1,4,1,4,2,8,2,8,2,8)
    R> d <- data.frame(g,v)
    R> d$cs <- ave(v, g, FUN=cumsum)
    R> d
       g v cs
    1  a 1  1
    2  b 4  4
    3  a 1  2
    4  b 4  8
    5  a 1  3
    6  b 4 12
    7  a 2  5
    8  b 8 20
    9  a 2  7
    10 b 8 28
    11 a 2  9
    12 b 8 36
    

提交回复
热议问题