cumsum in grouped data with dplyr

前端 未结 2 1983
北海茫月
北海茫月 2021-01-21 22:32

I have a data frame df (which can be downloaded here) referred to a register of companies that looks something like this:

    Provider.ID        Lo         


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-21 22:39

    When you group by local.Authority & year it takes unique values and print the result as 1,-1,1 so better group by only local.Authority where cumsum works based on total values and result 1,0,1

     df <- df %>%
          group_by(Local.Authority) %>%
          mutate(cum.to = cumsum(total))
    
        > df
        Source: local data frame [3 x 8]
        Groups: Local.Authority [1]
    
          Provider.ID Local.Authority month  year entry  exit total cum.to
                                  
        1 1-102642676            Kent    10  2010     1     0     1      1
        2 1-102642676            Kent     9  2011     0     1    -1      0
        3 1-102642676            Kent    10  2014     1     0     1      1
    

提交回复
热议问题