I am a bit puzzled here and must be missing something quite basic.
I want to extract columns from a multiple time series object. It can perhaps be done by making the ts object into a dataframe and then extracting them, but there is a direct way of subsetting time series as given in this question link
To figure out how to assign names to ts objects, ?ts shows
ts(data = NA, start = 1, end = numeric(), frequency = 1,
deltat = 1, ts.eps = getOption("ts.eps"), class = , names = )
but on running the code in ?ts help, with or without the names parameter gives
names(z) NULL.
z <- ts(matrix(rnorm(300), 100, 3), start=c(1961, 1), frequency=12)
or z <- ts(matrix(rnorm(300), 100, 3), start=c(1961, 1), frequency=12, names=c("x1", "x2", "x3"))
Main question: 1. How does one assign names to columns in time series objects ts and mts ?
2. What are the methods of extracting columns directly from time series object along with the time index? Is it necessary to convert it to zoo or xts class? or add the time index separately?
To give an idea of problem I am trying to solve:
# using inbuilt ldeaths time series dataset
ldeaths
d <- diff(ldeaths)
percen <- quantile(d, 0.9)
i <- ifelse(d>percen, 1,0)
signal <- cbind(d,i)
Now to extract the dataset for which the indicator is 1, with the time index,
I am not sure how to proceed. str(signal) is an mts object but printing signal shows no time index.
Thanks a lot.
Extracting the names of series in an
"mts"objectYou want
colnames():This is because
zis actually a matrix with extra attributes and matrices don’t havenamesbut they do havecolnames.Assigning/changing the names of series in an
"mts"objectTo assign
colnamesafter the fact or to change them use the replacement function'colnames<-'Extracting a particular series from an
"mts"objectAs for extracting columns,
[works just fine for"ts"and"mts"objects. for example:The guts of the OP’s problem
For the last bit, I’m not sure what you hope to get. A
"ts"or"mts"object is a regular time series and extracting the bits ofsignal[, "d"]results in a vector not a time series.There isn’t any time index because this is no longer a
"ts"object. If you want to do this, the zoo package is probably the way you want to go. Here is an example, where we convert to zoo object usingas.zoo()Then we can extract the observations we want (the names on which are a useful indicator of the time index)
and then a similar subsetting call but using the
index()to return the time index of the entire zoo object and then select out the bits we want