Using the application family on mts objects

Using apply (or sapply) in an mts object removes its time series properties when sent to the function. How should I apply the same function (with the input signal ts and ts output) in each of the time series in the mts object and return it (preferably in the form of mts) [I mean, except for use for loops]?

For example, suppose I write a function that returns the trend of a time series (using stl)

myfunc <- function(x) { return(stl(x,"per")$time.series[,2]) } 

Now for sample mts

 z <- ts(matrix(rnorm(90), 30, 3), start=c(1961, 1), frequency=4) class(z) 

Sending only one of the time series works correctly:

 myfunc(z[,1]) # works correctly, returns the trend of first series 

My function is not intended for multiple time series, therefore:

 myfunc(z) # will not work returning the error below Error in stl(x, "per") : only univariate series are allowed 

Using apply on an mts object, send each of the time series to the vector without saving its time series (tsp):

 apply(z,2,myfunc) # will not work returning the error below Error in stl(x, "per") : series is not periodic or has less than two periods 
+7
source share
2 answers

An easy way to do this is to work with indexes instead of pure apply :

 sapply(seq_len(ncol(z)),function(i) myfunc(z[,i])) 

apply places pure vectors inside the function because it first converts the object to a matrix. Using the function [ defined for time series objects, you are sure to retrieve the actual time series each time.

+8
source

I modify myfunc to check if it has a ts object as parameter x.

If x is not ts, it is converted to a ts object, since stl needs this type of parameter.

  myfunc <- function(x,...){ y <- x if(class(x) != 'ts') { dots <- c(...) y <- ts(x,start=c(dots[1], dots[2]), frequency=dots[3]) } return(stl(y,"per")$time.series[,2]) } ## no need to conversion (already ts object) myfunc(z[,1]) ## mts object ( here we give parameter necessary for conversion) apply(z,2,myfunc,1961,1,4) 
+3
source

All Articles