2012-07-30 72 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