R: Aggregating time series data returns NA

眉间皱痕 提交于 2019-12-11 04:13:23

问题


I'm trying to aggreagate data by 5 minute means by using xts:

library(xts)
data <- read.csv("C:/Users/User/Documents/data.csv")
times <- data$Time
X <- as.POSIXct(times)
X <- as.xts(X)
DataTable <- period.apply(X, endpoints(X, "minutes", 5), mean)

The problem is, if print out "DataTable", it shows that the aggregation didn't work, the aggregation scores are empty (NA).

2016-08-28 21:26:32   NA
2016-08-28 21:29:05   NA
2016-08-28 21:30:57   NA
2016-08-28 21:34:31   NA
2016-08-28 21:35:22   NA
2016-08-28 21:37:31   NA
2016-08-28 21:40:15   NA
2016-08-28 21:43:59   NA
2016-08-28 21:48:01   NA
2016-08-28 21:48:58   NA
2016-08-28 21:49:14   NA
2016-08-28 22:40:45   NA
2016-08-28 23:40:45   NA

Here is the input file: https://www.dropbox.com/s/epkbk770ajksqnb/data.csv?dl=0

Anybody know what I'm doing wrong?


回答1:


The problem was that you put X as the argument to aggregate rather than a numeric field (e.g. T1 or T2).

   library(xts)
    mydata    <- read.csv("data.csv")
    times     <- mydata$Time
    X         <- as.POSIXct(times)
    X         <- as.xts(X)
    period.apply(mydata$T1, INDEX = endpoints(X, "minutes", 5), function(x) mean(x, na.rm=T))



回答2:


The problem is that your xts object doesn't have any data because you created it with times only. Your first block of code is equivalent to:

library(xts)
data <- read.csv("C:/Users/User/Documents/data.csv")
X <- as.xts(as.POSIXct(data$Time))

Your period.apply call works just fine if you create an xts object with data.

X <- as.xts(read.zoo("C:/Users/User/Documents/data.csv", sep=",", header=TRUE))
DataTable <- period.apply(X, endpoints(X, "minutes", 5), mean)


来源:https://stackoverflow.com/questions/39190964/r-aggregating-time-series-data-returns-na

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