Cumulative total by group

后端 未结 4 1017
面向向阳花
面向向阳花 2020-12-18 03:09

For the following dataset:

d = data.frame(date = as.Date(as.Date(\'2015-01-01\'):as.Date(\'2015-04-10\'), origin = \"1970-01-01\"),
               group = re         


        
相关标签:
4条回答
  • 2020-12-18 03:24

    As this question was tagged with data.table, you are probably looking for (a modification of @Franks comment).

    setDT(d)[order(date), new := cumsum(value), by = group]
    

    This will simultaneously rearrange the data by date (not sure if needed, if not, you can get rid of order(date)) and update your data set in place utilizing the := operator

    0 讨论(0)
  • 2020-12-18 03:32

    Is this it?

    sp <- split(d, d$group)
    res <- lapply(seq_along(sp), function(i) cumsum(sp[[i]]$value))
    res <- lapply(seq_along(res), function(i){
            sp[[i]]$c.sum <- res[[i]]
            sp[[i]]
        }) 
    res <- do.call(rbind, res)
    res
    
    0 讨论(0)
  • 2020-12-18 03:40

    This should work

    library(dplyr)
    d %>% 
      group_by(group) %>% 
      arrange(date) %>% 
      mutate(Total = cumsum(value))
    
    0 讨论(0)
  • 2020-12-18 03:45

    If you just want cumulative sums per group, then you can do

    transform(d, new=ave(value,group,FUN=cumsum))
    

    with base R.

    0 讨论(0)
提交回复
热议问题