我有一个数据帧,它在日期列中包含DateTime值,在三个列中包含每个日期时间的计数。R中的每小时组数据帧
我想对数据进行分组小时与三列
聚合函数适用于单一的列数,但我想这样做对整个数据帧。有小费吗?
aggregate(DateFreq$ColA,by=list((substr(DateFreq$Date,1,13))),sum)
我有一个数据帧,它在日期列中包含DateTime值,在三个列中包含每个日期时间的计数。R中的每小时组数据帧
我想对数据进行分组小时与三列
聚合函数适用于单一的列数,但我想这样做对整个数据帧。有小费吗?
aggregate(DateFreq$ColA,by=list((substr(DateFreq$Date,1,13))),sum)
您可以使用aggregate
的formula
。但是你应该正确创建一个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
您可以使用dplyr
使用dplyr::group_by
和dplyr::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
你应该提供数据的重复的例子。这里的人应该复制并粘贴您的代码并将其复制。 – agstudy
对不起,我会记住这一点。 – ganeshran