Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
795 views
in Technique[技术] by (71.8m points)

object - R aggregate data.frame with date column

I have the data frame resambling the one in the below

Date       Expenditure Indicator
29-01-2011 5455        212
25-01-2012 5452        111
11-02-2011 365         5

I'm currently interested in summing up the Expenditure values, I'm trying to use the function below

dta.sum <- aggregate(x = dta, FUN = sum, 
                         by = list(Group.date = dta$date))

but R returns the following error, Error in Summary.Date(c(15614L, 15614L, 15614L, 15614L, 15614L, 15614L, : sum not defined for "Date" objects. The Date column was previously defined as date with use of the as.Date function. Analogous function but with the mean works fine.

dta.sum <- aggregate(x = dta, FUN = mean 
                             by = list(Group.date = dta$date))

I would like to keep date formatted as date.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Indicate the variables you are trying to get the aggregate of in your aggregate statement, and this problem should be resolved:

dta.sum <- aggregate(x = dta[c("Expenditure","Indicator")],
                     FUN = sum,
                     by = list(Group.date = dta$Date))

EDITED TO ADD EXPLANATION: When you give the aggregate argument as just dta, aggregate attempts to apply the argument to every column. sum is not defined for date values in R, and therefore you are getting errors. You want to exclude the grouping column by using the code described above.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...