Using Apply family of functions on mts objects

岁酱吖の 提交于 2019-12-05 05:17:10

A simple way around this, is to work with the indices instead of a clean apply :

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

apply puts clean vectors inside the function, because it first converts an object to a matrix. By using the [ function defined for time series objects, you are sure that you extract a valid time series each time.

I change the myfunc to check if it have a ts object as parameter x.

If x is not a ts , it is converted to ts object as stl need this parameter type.

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