2016-07-10 103 views
1

免責聲明 - 標題可能會引起誤解 - 我認爲我之所以沒有找到解決方案的部分原因是我並不完全知道該怎麼去Google。通過多個分組添加變量計數

我有一個擴展格式的組級數據集;年,國家代碼重複每個組(ID),如以下(手動輸入)

year country id v1 v2 v3 
1991 20  1 1 0 0 
1991 20  2 0 1 0 
1991 20  3 0 0 1 
1991 20  4 1 0 0 
1991 20  5 1 0 0 
1991 20  6 0 1 0 

我想在最後添加國家年計爲列,以便它看起來像下面

year country id v1 v2 v3 v1.count v2.count v3.count 
1991 20  1 1 0 0  3   2   1 
1991 20  2 0 1 0  3   2   1 
1991 20  3 0 0 1  3   2   1 
1991 20  4 1 0 0  3   2   1 
1991 20  5 1 0 0  3   2   1 
1991 20  6 0 1 0  3   2   1 

我試過aggregate,countdplyr沒有成功。我以爲Group by and conditionally countFrequency count for a specific category可能會訣竅,但我無法讓它工作。我怎樣才能做到這一點?

+0

'df $ v1.count < - sum(df $ v1)'? – 989

+0

這會在'df'中總結所有年份和國家的'v1',不是嗎? – rfsrc

回答

1

我們可以通過「年」和「國家」

df1 %>% 
    group_by(year, country) %>% 
    mutate_each(funs(count = sum), v1:v3) 
# year country id v1 v2 v3 v1_count v2_count v3_count 
# <int> <int> <int> <int> <int> <int> <int> <int> <int> 
#1 1991  20  1  1  0  0  3  2  1 
#2 1991  20  2  0  1  0  3  2  1 
#3 1991  20  3  0  0  1  3  2  1 
#4 1991  20  4  1  0  0  3  2  1 
#5 1991  20  5  1  0  0  3  2  1 
#6 1991  20  6  0  1  0  3  2  1 
+1

謝謝,我之前用'mutate'試過了,這個是做我需要的。 – rfsrc

0

分組後使用從dplyrmutate_each我猜你也可以只使用mutate

df1 <- read.table(text="year country id v1 v2 v3 
1991 20  1 1 0 0 
1991 20  2 0 1 0 
1991 20  3 0 0 1 
1991 20  4 1 0 0 
1991 20  5 1 0 0 
1991 20  6 0 1 0", head=T, as.is=T) 

df1 

library(dplyr) 

df1 %>% group_by(year, country) %>% 
    mutate(v1.count=sum(v1), v2.count=sum(v2), v3.count=sum(v3)) 
# Source: local data frame [6 x 9] 
# Groups: year, country [1] 

# year country id v1 v2 v3 v1.count v2.count v3.count 
# (int) (int) (int) (int) (int) (int) (int) (int) (int) 
# 1 1991  20  1  1  0  0  3  2  1 
# 2 1991  20  2  0  1  0  3  2  1 
# 3 1991  20  3  0  0  1  3  2  1 
# 4 1991  20  4  1  0  0  3  2  1 
# 5 1991  20  5  1  0  0  3  2  1 
# 6 1991  20  6  0  1  0  3  2  1 
+0

嗨,我認爲它適用於'sum',正如其他評論者所建議的那樣,但我也希望將它用於連續變量(例如'ineq'),而不僅僅用於二進制變量。 – rfsrc