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

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

问题描述

我有一个数据框,它在日期列中有 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) 

推荐答案

你可以使用aggregateformula.但是你应该在之前正确创建一个 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 中每小时对数据框进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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