2012-07-30 59 views
0

我想根據月份總結數據。例如,我有這樣的數據集:根據月份r的總列數

x 
     Date App Vol 
1 2010-01-30 A 100 
2 2010-01-28 B 140 
3 2010-01-30 C 160 
4 2010-02-28 A 110 
5 2010-02-28 B 120 
6 2010-02-28 C 300 

我希望能夠每月彙總應用數據。根據上述的數據幀, A應該是210,B = 260,C = 460等

我使用聚集函數ASE的下方,但得到錯誤:

y<-aggregate(x$Vol, list(Month = format(as.POSIXct(x$Date), "%Y-%m")), sum) 

任何想法?

+0

這是我在帖子末尾的錯字,這不是問題。 – 2012-07-30 13:59:57

+0

@Mike使用ttmaccer的建議和你的代碼它適用於我。 – 2012-07-30 14:01:59

+0

@Tyler Rinker,我得到這個錯誤:Summary.factor(c(1L,3L,6L,36L),na.rm = FALSE)中的錯誤: 總和對因子 – 2012-07-30 14:03:21

回答

1

開始轉向Vol爲數字(它弄亂不知):

x$Vol <- as.numeric(as.character(x$Vol)) 

我可以通過打開Vol成因素重現您eror如下所示:

x$Vol <- as.factor(x$Vol) 
aggregate(x$Vol, list(x$App), sum) 

#> aggregate(x$Vol, list(x$App), sum) 
#Error in Summary.factor(1:2, na.rm = FALSE) : 
# sum not meaningful for factors 

而且你說:

I would like to be able to summary App data by each month. According to the 
data frame above, A should be 210, B = 260, C=460 etc. 

如果是這種情況,請使用:

x$Month <- format(as.POSIXct(x$Date), "%Y-%m") 
aggregate(x$Vol, list(x$Month, x$App), sum) 

否則使用ttmacer的建議。

+0

是的,我必須將我的x $ Vol轉換爲數字。非常棒。謝謝。 – 2012-07-30 14:19:00

0
x<-read.table(header=T,text="Date  App Vol 
    1 2010-01-30 A  100 
    2 2010-01-28 B  140 
    3 2010-01-30 C  160 
    4 2010-02-28 A  110  
    5 2010-02-28 B   120  
    6 2010-02-28 C   300") 



y<-aggregate(x$Vol, list(Month = format(as.POSIXct(x$Date), "%Y-%m")), sum) 
y<-aggregate(x$Vol, list(x$App), sum) 

嘗試使用此數據。

+0

我總是收到此錯誤:Summary.factor(c(1L,3L,6L,36L),na中的錯誤。 rm = FALSE): 總和對因素無意義 – 2012-07-30 14:11:17