2016-11-29 34 views
1

我目前正在研究一個項目,考察員工流失率。到目前爲止,我已經創建了一個表,看起來像下面的示例:R - 按位置計算每月的團隊規模總數

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) 

我想通過採取基於位置和月Net_Change列的總和來計算團隊規模(按順序排列)。例如,倫敦2月隊的規模應該等於8(1 + 7),而3月隊的規模應該等於4(1 + 7-4)。

我已經嘗試過使用dplyr'summarize'函數來做這件事,但不成功。如果'tidyverse'方法適用,那將是很棒的。

非常感謝您的幫助!

+2

看來你正在尋找'cumsum()'。 – jazzurro

+1

感謝那 – George

回答

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

# Month Location Joiners Leavers Net_Change Team_size 
# (fctr) (fctr) (dbl) (dbl)  (dbl)  (dbl) 
#1 Jan Sheffield  7  1   6   6 
#2 Feb Sheffield  3  5   -2   4 
#3 March Sheffield  8  9   -1   3 
#4 Jan London  4  3   1   1 
#5 Feb London  9  2   7   8 
#6 March London  1  5   -4   4 
+0

謝謝你,太棒了。從來沒有見過這種功能,所以這是有幫助的。爲了達到這個目的,重要的是行按月排序? – George

+0

@喬治遺憾的迴應遲到..不,不需要訂購。輸出按照數據的順序顯示。我沒有執行任何明確的排序。 –

+0

沒問題。謝謝你的解決方案完美運作:) – George