在R中每小时对Dataframe进行分组 [英] Group Dataframe hourly in R

查看:146
本文介绍了在R中每小时对Dataframe进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,该数据框在date列和三列中都有DateTime值,每个日期时间都有计数。

I have a dataframe which has DateTime values in the date column and three columns with the counts for each date time.

我试图按小时将数据分组这三列的计数

I am trying to group the data hourly with the counts of the three columns

聚合函数适用于单列,但我正在尝试针对整个数据帧执行此操作。

The aggregate function works for single columns but I am trying to do it for the entire data frame. Any tips?

aggregate(DateFreq$ColA,by=list((substr(DateFreq$Date,1,13))),sum) 


推荐答案

您可以使用总计中的>公式。但是,您应该在之前正确创建一个 hour 变量。

You can use formula of the aggregate. But you should create correctly an hour variable before.

dat$hour <- as.POSIXlt(dat$Date)$hour
aggregate(.~hour,data=dat,sum)

此处为示例:

Lines <- "Date,c1,c2,c3
06/25/2013 12:01,0,1,1
06/25/2013 12:08,-1,1,1
06/25/2013 12:48,0,1,1
06/25/2013 12:58,0,1,1
06/25/2013 13:01,0,1,1
06/25/2013 13:08,0,1,1
06/25/2013 13:48,0,1,1
06/25/2013 13:58,0,1,1
06/25/2013 14:01,0,1,1
06/25/2013 14:08,0,1,1
06/25/2013 14:48,0,1,1
06/25/2013 14:58,0,1,1"

library(zoo)  ## better to read/manipulate time series
z <- read.zoo(text = Lines, header = TRUE, sep = ",",
              index=0:1,tz='',
              format = "%m/%d/%Y %H:%M")


dat <- data.frame(Date = index(z),coredata(z))
dat$hour <- as.POSIXlt(dat$Date)$hour
aggregate(.~hour,data=dat,sum)

hour       Date c1 c2 c3
1   12 5488624500 -1  4  4
2   13 5488638900  0  4  4
3   14 5488653300  0  4  4

这篇关于在R中每小时对Dataframe进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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