强制 xts() 对象到 ts()

Force xts() object to ts()

数据:DOWNLOAD .TXT

代码:

data = read.table("DistrBdaily1yrs.txt", header = TRUE, sep = "", dec = ",")
data$DATE = as.Date(as.character(data$DATE),format="%Y%m%d") 
dataXts = xts(data$QUANTITY,data$DATE, frequency = 6)   

tseries = ts(dataXts, start = start(dataXts), end = end(dataXts), frequency = 6)

我想要做的是将 xts dataXts 对象转换为具有正确开始和结束日期的 ts 对象,以便使用 decompose 函数。在这种情况下 start = start(dataXts)end = end(dataXts) 给了我正确的开始和结束日期,但 tseries 不识别 dataXts 中的数据列,然后认为所有都是数据。

我该如何解决这个问题?

我不确定我是否能够 "FORCE" xtsts 但我得到了 decompose 部分功能:

library("data.table")
# I was unable to read-in using read.table() for some reason.... used fread() as it is much faster
data <- fread("DistrBdaily1yrs.txt", header = TRUE, sep="\t")

# Set column names to the ones I saw on dropbox, as i was unable to read-in header for some reason!
colnames(data) <- c("DATE", "QUANTITY")

# Keep as-is 
data$DATE = as.Date(as.character(data$DATE),format="%Y%m%d") 
dataXts = xts(data$QUANTITY,data$DATE, frequency = 6)   

# Not sure what the "QUANTITY" Column means but it must be turned into "numeric"
# You can see this post on how to do it if the following is unsatisfactory:
# 
a<-as.numeric(gsub(",",".",dataXts))

dataXts <- reclass(a, match.to=dataXts); colnames(dataXts)<- "QUANTITY"


# Now convert it to timeSeries
timeseries <- ts(dataXts,frequency=6)

# decompose
decompose(timeseries)

此外,当我将 xts 转换为 ts 时,我假设它将使用第一个和最后一个日期来构造 ts 这就是为什么我遗漏了 start = start(dataXts), end = end(dataXts)ts() 函数中。另请参阅 ?ts,因为您不能在 startend 条件中传递 Dates,而是:

Either a single number or a vector of two integers, which specify a natural time unit and a (1-based) number of samples into the time unit.

您始终可以使用重新分类转换回 xts

# for example: Say you only want the trend
reclass(decompose(timeseries)$trend,match.to=dataXts)