间隔5分钟的时间为15分钟的时间间隔的平均数据
问题描述:
我具有如用5分钟的时间间隔波纹管提到的数据帧:间隔5分钟的时间为15分钟的时间间隔的平均数据
df
Time P_21 P_22P_23P_24
1/1/2014 0:00 50 60 40 30
1/1/2014 0:05 100 120 80 60
1/1/2014 0:10 150 180 120 90
1/1/2014 0:15 45 52 36 32
1/1/2014 0:20 90 104 72 64
1/1/2014 0:25 135 156 108 96
1/1/2014 0:30 42 56 39 31
1/1/2014 0:35 84 112 78 62
1/1/2014 0:40 126 168 117 93
1/1/2014 0:45 50 60 40 30
1/1/2014 0:50 50 60 40 30
1/1/2014 0:55 50 60 40 30
1/1/2014 1:00 50 60 40 30
1/1/2014 1:05 50 60 40 30
我想使15分钟间隔以其平均值
Time P_21P_22P_23P_24
1/1/2014 0:00 100 120 80 60
1/1/2014 0:15 90 104 72 64
1/1/2014 0:30 84 112 78 62
1/1/2014 0:45 50 60 40 30
1/1/2014 1:00 continue continue continue continue
它将取平均值00,05和10(3数据)。 请帮我解决这个问题。
答
使用xts
包,阅读你的数据作为一个真正的时间序列:
library(xts)
dx <- read.zoo(text='1/1/2014 0:00 50 60 40 30
1/1/2014 0:05 100 120 80 60
1/1/2014 0:10 150 180 120 90
1/1/2014 0:15 45 52 36 32
1/1/2014 0:20 90 104 72 64
1/1/2014 0:25 135 156 108 96
1/1/2014 0:30 42 56 39 31
1/1/2014 0:35 84 112 78 62
1/1/2014 0:40 126 168 117 93
1/1/2014 0:45 50 60 40 30
1/1/2014 0:50 50 60 40 30
1/1/2014 0:55 50 60 40 30
1/1/2014 1:00 50 60 40 30
1/1/2014 1:05 50 60 40 30',index=1:2,tz='',format="%d/%m/%Y %H:%M")
那么得心应手period.apply
收集您的TS为每个时间段:
period.apply(dx,endpoints(dx,on = "mins",k=15),mean)
# V3 V4 V5 V6
# 2014-01-01 00:10:00 100 120 80 60
# 2014-01-01 00:25:00 90 104 72 64
# 2014-01-01 00:40:00 84 112 78 62
# 2014-01-01 00:55:00 50 60 40 30
# 2014-01-01 01:05:00 50 60 40 30
答
这里有一个替代使用data.table
包
library(data.table)
setDT(df)[, Time := Time[1L],
by = cumsum(as.POSIXlt(Time, format = "%m/%d/%Y %H:%M")$min %% 15 == 0)]
df[, lapply(.SD, mean), by = Time]
# Time P_21 P_22 P_23 P_24
# 1: 1/1/2014 0:00 100 120 80 60
# 2: 1/1/2014 0:15 90 104 72 64
# 3: 1/1/2014 0:30 84 112 78 62
# 4: 1/1/2014 0:45 50 60 40 30
# 5: 1/1/2014 1:00 50 60 40 30
+0
@DolaIslam,如果你对某个解决方案感到满意,你应该通过检查左边的复选标记来接受它。 – agstudy 2015-03-31 10:16:22
谢谢s ir为您的评论。在这里我使用POSIXct作为时间格式。你能说我怎么能继续我的数据框架。再次感谢。 – 2015-03-30 21:02:14
@DolaIslam对不起,我没有明白你的意思。你想强制xts对象到data.frame? 'data.frame(time = index(dx),coredata(dx))' – agstudy 2015-03-30 21:12:01
它正在工作....非常感谢。现在我读了动物园和它的伟大的 – 2015-03-30 21:31:35