George - 1 year ago 106
R Question

# R - Calculating a Running Total of Team Size by Location for each Month

I am currently working on a project looking at employee turnover rates. So far I have created a table that looks like the following sample:

``````library(tidyverse)

Data <- data.frame(Month = c("Jan", "Feb", "March", "Jan", "Feb", "March"),
Location = c("Sheffield", "Sheffield", "Sheffield","London", "London", "London"),
Joiners = c(7,3,8,4,9,1),
Leavers = c(1,5,9,3,2,5)) %>%
mutate(Net_Change = Joiners - Leavers)
``````

I am wanting to calculate the team size by taking the sum of the Net_Change column based on Location and month (in order of sequence). For example, the February team size for London should equal 8 (1+7) and the March team size should equal 4 (1+7-4).

I have tried doing this using the dplyr 'summarise' function but was unsuccessful. If a 'tidyverse' method is applicable that would be great.

Thanks a lot for your help on this!

``````Data %>% group_by(Location) %>% mutate(Team_size = cumsum(Net_Change))