R聚合带日期列的data.frame [英] R aggregate data.frame with date column

查看:110
本文介绍了R聚合带日期列的data.frame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面重新设置数据框的大小

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))

,但是R返回以下错误, Summary.Date(c(15614L,15614L,15614L,15614L,15614L,15614L,:和不 Date 列以前使用 as.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.

推荐答案

在您的聚合语句中指示要获取其聚合的变量,并且应该解决此问题:

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))

编辑以添加说明:当您将 aggregate 参数仅设置为 dta 时,聚合尝试将参数应用于每个列。没有为R中的日期值定义 sum ,因此会出现错误。您想使用上述代码排除分组列。

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.

这篇关于R聚合带日期列的data.frame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆