I have this simplified df
that I'm tryng to get the cumsum()
for each group
library(dplyr)
Country <- c(rep("A",5), rep("B",4), rep("C", 5))
Date <- 1:14
Value <- c(2:6, 10:13, 7:11)
df <- data.frame(Date, Country, Value)
> view(df)
Date Country Value
1 A 2
2 A 3
3 A 4
4 A 5
5 A 6
6 B 10
7 B 11
8 B 12
9 B 13
10 C 7
11 C 8
12 C 9
13 C 10
14 C 11
I know it seems like a repeated question, but I'm doing the following and don't know why isn't working. Instead of the cumulative sum by group, I'm getting the cumsum
of all column:
df_sum <- df%>%
group_by(Country) %>%
mutate(Sum = cumsum(Value))
Date Country Value Sum
<int> <chr> <int> <int>
1 A 2 2
2 A 3 5
3 A 4 9
4 A 5 14
5 A 6 20
6 B 10 30
7 B 11 41
8 B 12 53
9 B 13 66
10 C 7 73
11 C 8 81
12 C 9 90
13 C 10 100
14 C 11 111