2011-11-07 166 views
2

我的按日期對陣各隊進球一個數據幀(DF)R.彙總數據,而不合並

gamedate teamID Gls 
1992-08-22 CHL 3 
1992-08-22 MNU 1 
1992-08-23 ARS 0 
1992-08-23 LIV 2 
1992-08-24 MNU 0 
1992-08-25 LIV 2 
1992-08-26 ARS 0 
1992-08-26 CHL 0 

我希望生產這表明玩過遊戲的人數彙總表和 一些遊戲這些球隊都消隱

gamedate games blanks 
1992-08-22 2  0 
1992-08-23 2  1 
1992-08-24 1  1 
1992-08-25 1  0 
1992-08-26 2  2 

我可以得到遊戲和空格分開使用ddply

df.a <- ddply(df,"gamedate",function(x) c(count=nrow(x))) 
df.b <- ddply(subset(df,Gls==0),"gamedate",function(x) c(count=nrow(x))) 
01在每個日期反對派

然後合併df.a和df.b以獲得我的答案。不過,我相信必須有一個更 簡單而優雅的解決方案

回答

3

你只需要使用summarise

讀入的數據:

dat <- read.table(textConnection("gamedate teamID Gls 
    1992-08-22 CHL 3 
    1992-08-22 MNU 1 
    1992-08-23 ARS 0 
    1992-08-23 LIV 2 
    1992-08-24 MNU 0 
    1992-08-25 LIV 2 
    1992-08-26 ARS 0 
    1992-08-26 CHL 0"),sep = "",header = TRUE) 

,然後調用ddply

ddply(dat,.(gamedate),summarise,tot = length(teamID),blanks = length(which(Gls == 0))) 
    gamedate tot blanks 
1 1992-08-22 2  0 
2 1992-08-23 2  1 
3 1992-08-24 1  1 
4 1992-08-25 1  0 
5 1992-08-26 2  2 
+0

早起的鳥等感謝。 – pssguy

2

你唯一缺少的是將你的函數包裝在data.frame()調用中, lumn的名字...和列名是可選的:)

我使用@ joran的dat data.frame,因爲它允許我測試我的答案。

ddply(dat, "gamedate", function(x) data.frame( 
             tot = nrow(x), 
             blanks = nrow(subset(x, Gls == 0)) 
              ) 
    ) 

順便說一句,我的上述滑稽格式只是爲了防止它在屏幕上滾動,並幫助說明如何我真的只是彙集已創建的功能。

+0

+1我幾乎在那裏.... Tx – pssguy

1

另一個解決方案使用簡單的aggregate。我正在使用喬蘭的dat

agg <- aggregate(cbind(1, dat$Gls==0), list(dat$gamedate), sum) 
names(agg) <- c("gamedate", "games", "blanks") 
agg 
+0

+1的聚合解決方案。你能解釋一下cbind(1,...)在做什麼嗎?它只是充當「櫃檯」嗎? –

+0

@DWin'cbind'增加了一列1,然後他可以求和來計算行數。這樣兩個值都是總和。 –

+0

嗯。我用tapply做過這樣的事情,所以我猜它應該對我更明顯。 –