6

我有一个数据框,它在日期列中有 DateTime 值,三列中有每个日期时间的计数。

我正在尝试使用三列的计数每小时对数据进行分组

样本数据

聚合函数适用于单列,但我正在尝试对整个数据框执行此操作。有小费吗?

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

2 回答 2

5

您可以使用anddplyr进行聚合:dplyr::group_bydplyr::summarise

library(lubridate)
library(anytime)
library(tidyverse)

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"

setClass("myDate")
setAs("character","myDate", function(from) anytime(from))
df <- read.csv(text = Lines, header=TRUE,  colClasses = c("myDate", "numeric", "numeric", "numeric"))

df %>%
  group_by(Date=floor_date(Date, "1 hour")) %>%
  summarize(c1=sum(c1), c2=sum(c2), c3=sum(c3))
# A tibble: 3 × 4
                 Date    c1    c2    c3
               <dttm> <dbl> <dbl> <dbl>
1 2013-06-25 12:00:00    -1     4     4
2 2013-06-25 13:00:00     0     4     4
3 2013-06-25 14:00:00     0     4     4
于 2017-05-18T19:45:39.590 回答
4

您可以使用formula. aggregate但是你应该hour在之前正确地创建一个变量。

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
于 2013-07-05T11:31:03.693 回答