I have xts
time-series object for 10 days of data. The data is sampled at minutes frequency. Therefore, for each day, I have 1440 observations. I need to coerce
library(xts)
library(ggplot2)
library(reshape2)
set.seed(42)
timevalues = "20150101 0000/20150110 2359"
timesequence <- timeBasedSeq(timevalues)
min_data <- xts(rnorm(14400),timesequence)
ts_data <- ts(as.numeric(min_data), frequency = 1440)
out <- stl(ts_data, s.window = "per")
time.series <- as.data.frame(cbind(ts_data, out$time.series))
colnames(time.series) <- c("Data", "Seasonal", "Trend", "Remainder")
time.series$Date <- timesequence
time.series <- melt(time.series, 'Date')
ggplot(time.series, aes(x=Date, y=value)) +
geom_line() +
facet_free(variable~.)
i think what you are looking for is the below:
xts2ts <- function(XD) {
maxRow <- nrow(XD)
startYM <- c(.indexyear(XD[1]) + 1900, .indexmon(XD[1]) + 1L)
endYM <- c(.indexyear(XD[maxRow]) + 1900, .indexmon(XD[maxRow]) + 1L)
ts(as.numeric(XD), start = startYM, end = endYM, frequency = 12L)
}
If you hav a xts data in monthly, quarterly and yearly frequency it maby be useful (use packages: xts, stats, data.table, zoo)
xts_ts <- function(xts_data) {
freq_list <-
data.table::data.table(
freq = c('month', 'quarter', 'year'),
freq_n = c(12L, 4L, 1L),
freq_format = c('%Y, %m', '%Y, %q', '%Y')
)
d_ferq <- xts::periodicity(xts_data)[["label"]]
freq_n <- freq_list[freq == d_ferq, freq_n]
freq_format <- freq_list[freq == d_ferq, freq_format]
# Put NA if missing date
empty <-
zoo::zoo(order.by = seq.Date(zoo::index(xts_data)[1], zoo::index(xts_data)[nrow(xts_data)], by = d_ferq))
no_misssing <- merge(xts_data, empty)
if (d_ferq == 'quarter') {
start_date <-
format(zoo::as.yearqtr(xts::periodicity(xts_data)[["start"]]), freq_format)
} else {
start_date <-
format(zoo::as.Date(xts::periodicity(xts_data)[["start"]]), freq_format)
}
stats::ts(zoo::coredata(no_misssing),
start = as.integer(strsplit(start_date, split = ',')[[1]]),
frequency = freq_n)
}
I recently have discovered a package called "tsbox".
It promises easy conversion between time series types. (here a tutorial: https://cran.r-project.org/web/packages/tsbox/vignettes/tsbox.html)
Might be useful in cases like this one.
Here an example:
library(tsbox)
nowTS <-ts_ts(formerXTS)
or the other way round if you want to convert the ts back to an xts series
library(tsbox)
nowXTS <-ts_xts(nowTS)
An xts-only solution, based on an idea I had from looking at Pascal's answer.
library(xts)
set.seed(42)
timevalues = "20150101 0000/20150110 2359"
timesequence <- timeBasedSeq(timevalues)
min_data <- xts(rnorm(14400),timesequence)
ts_data <- ts(as.numeric(min_data), frequency = 1440)
out <- stl(ts_data, s.window = "per")
ts_out <- merge(min_data, out$time.series)
plot.zoo(ts_out)