r two xts operations

纵饮孤独 提交于 2019-12-02 20:45:40

问题


Two hourly time series xts1 and xts2, xts1 has some missing times.

xts1
time                   speed power
2010-01-01 00:00:00     0.1  1.1
2010-01-01 01:00:00     0.2  1.2
2010-01-01 05:00:00     0.2  1.2
.....

xts2
time                   speed power
2010-01-01 00:00:00     0.1  1.1
2010-01-01 01:00:00     0.2  1.2
2010-01-01 02:00:00     0.2  1.2
.....

When combine them into one file(get the average of speed, and sum the power based on the same timestamp), get non--conformable arrays error. The command used was:

hourly.data.table = data.table (time = time(xts1), meanspeed=    (coredata(xts1$speed)+coredata(xts2$speed))/2, power= coredata(xts1$power)+coredata(xts2$power))

How to do this combination by time? Thanks in advance.


回答1:


Try

library(xts)
xts1 <- xts(df1[-1], order.by = as.POSIXct(df1$time))
xts2 <- xts(df2[-1], order.by = as.POSIXct(df2$time))
res <- xts1+xts2
res[,1] <- res[,1]/2
res
#                     speed power
#2010-01-01 00:00:00   0.1   2.2
#2010-01-01 01:00:00   0.2   2.4

data

df1 <- structure(list(time = c("2010-01-01 00:00:00", 
"2010-01-01 01:00:00", 
"2010-01-01 05:00:00"), speed = c(0.1, 0.2, 0.2), power = c(1.1, 
1.2, 1.2)), .Names = c("time", "speed", "power"), 
class = "data.frame", row.names = c(NA, -3L))

df2 <- structure(list(time = c("2010-01-01 00:00:00", 
"2010-01-01 01:00:00", 
"2010-01-01 02:00:00"), speed = c(0.1, 0.2, 0.2), power = c(1.1, 
1.2, 1.2)), .Names = c("time", "speed", "power"), 
class = "data.frame", row.names = c(NA, -3L))


来源:https://stackoverflow.com/questions/29779138/r-two-xts-operations

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!