如何在R中按组平均时间序列
我的数据集如下所示:如何在R中按组平均时间序列,r,time,average,R,Time,Average,我的数据集如下所示: datetime <- seq.POSIXt(from=as.POSIXct("2017-05-09 11:45:01", tz="GMT"), to=as.POSIXct("2017-05-09 12:45:00", tz="GMT"), by="sec") group <- rep(1:120, each = 30) sample.dat <- data.frame(datetime,group) head(sample.da
datetime <- seq.POSIXt(from=as.POSIXct("2017-05-09 11:45:01", tz="GMT"),
to=as.POSIXct("2017-05-09 12:45:00", tz="GMT"), by="sec")
group <- rep(1:120, each = 30)
sample.dat <- data.frame(datetime,group)
head(sample.dat)
datetime group
1 2017-05-09 11:45:01 1
2 2017-05-09 11:45:02 1
3 2017-05-09 11:45:03 1
4 2017-05-09 11:45:04 1
5 2017-05-09 11:45:05 1
6 2017-05-09 11:45:06 1
我尝试过使用aggregate()
,但返回的日期时间列的格式是数字,例如:
group date
1 1 1493984723
2 2 1493984753
3 3 1493984783
4 4 1493984813
5 5 1493984843
6 6 1493984873
那么,如何按组平均所需输出格式中的时间呢
library(dplyr)
sample.dat %>% group_by(group) %>% summarise(mean(datetime))
# A tibble: 120 × 2
group `mean(datetime)`
<int> <dttm>
1 1 2017-05-09 11:45:15
2 2 2017-05-09 11:45:45
3 3 2017-05-09 11:46:15
4 4 2017-05-09 11:46:45
5 5 2017-05-09 11:47:15
库(dplyr)
sample.dat%>%分组依据(分组)%>%汇总(平均(日期时间))
#一个tibble:120×2
组平均值(日期时间)`
1 1 2017-05-09 11:45:15
2 2 2017-05-09 11:45:45
3 3 2017-05-09 11:46:15
4 4 2017-05-09 11:46:45
5 5 2017-05-09 11:47:15
聚合
似乎有效
aggregate(sample.dat$datetime,FUN=mean,by=list(group))
# Group.1 x
# 1 1 2017-05-09 14:45:15
# 2 2 2017-05-09 14:45:45
# 3 3 2017-05-09 14:46:15
# 4 4 2017-05-09 14:46:45
# 5 5 2017-05-09 14:47:15
# 6 6 2017-05-09 14:47:45
嗯,这很奇怪,当我使用聚合时,我得到了datetime列的奇怪数字格式。可能是因为我使用了错误的代码(cbind(datetime)~group)
aggregate
对我也适用。话虽如此,我以前见过数字转换,但现在无法复制它。。。
aggregate(sample.dat$datetime,FUN=mean,by=list(group))
# Group.1 x
# 1 1 2017-05-09 14:45:15
# 2 2 2017-05-09 14:45:45
# 3 3 2017-05-09 14:46:15
# 4 4 2017-05-09 14:46:45
# 5 5 2017-05-09 14:47:15
# 6 6 2017-05-09 14:47:45