R: Calculate cumulative sums and counts since the last occurrence of a value

送分小仙女□ 提交于 2019-12-05 23:32:07

We can use dplyr. Grouped by 'user_id' and a grouping variable created by taking the cumulative sum of 'pit' and getting its lag, we get the cumsum of 'cost' as 'cum_cost' and the cummax of index of match between the 'category' and unique 'category' as 'distinct_categories.

library(dplyr)
df %>%
    group_by(user_id, ind= lag(cumsum(pit), default=0)) %>% 
    mutate(cum_cost = cumsum(cost), 
           distinct_categories = cummax(match(category, unique(category))))
# user_id order_id  cost category   pit   ind cum_cost distinct_categories
#     <int>    <int> <dbl>    <chr> <int> <dbl>    <dbl>               <int>
#1        1        3  49.8   apples     0     0     49.8                   1
#2        1       13  14.8  chicken     0     0     64.6                   2
#3        1       18  11.4   apples     0     0     76.0                   2
#4        1       15  52.6  chicken     0     0    128.6                   2
#5        1       11  13.6  chicken     1     0    142.2                   2
#6        1       19  26.9  chicken     0     1     26.9                   1
#7        1        2  54.9  chicken     0     1     81.8                   1
#8        1        1  70.6  chicken     0     1    152.4                   1
#9        1       10  55.0  chicken     0     1    207.4                   1
#10       1       12  19.7  chicken     1     1    227.1                   1
#11       2        8  40.0    pears     0     2     40.0                   1
#12       2       16  37.4    pears     0     2     77.4                   1
#13       2       20  70.5    pears     0     2    147.9                   1
#14       2        5  63.8   apples     0     2    211.7                   2
#15       2       14  31.9   apples     1     2    243.6                   2
#16       2       17   9.1  chicken     0     3      9.1                   1
#17       2        4  21.9    pears     0     3     31.0                   2
#18       2        7  52.3   apples     0     3     83.3                   3
#19       2        9  43.3  chicken     0     3    126.6                   3
#20       2        6   9.9    pears     1     3    136.5                   3
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!