在mts对象上使用Apply系列函数

Maj*_*ian 7 r apply

在mts对象上使用apply(或sapply)会在发送到函数时删除其时间序列属性.我应该如何在mts对象的每个时间序列上应用相同的函数(使用ts输入和ts输出)并返回它(最好是mts)[我的意思是除了使用for循环]?

例如,假设我编写了一个返回时间序列趋势的函数(使用stl)

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

现在有一个样本mts

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

只发送其中一个时间序列是正确的:

myfunc(z[,1]) # works correctly, returns the trend of first series
Run Code Online (Sandbox Code Playgroud)

我的功能不适用于多个时间序列,因此:

myfunc(z) # will not work returning the error below

Error in stl(x, "per") : only univariate series are allowed
Run Code Online (Sandbox Code Playgroud)

在mts对象上使用apply将每个时间序列作为向量发送,而不是保留其时间序列属性(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
Run Code Online (Sandbox Code Playgroud)

Jor*_*eys 8

解决这个问题的一个简单方法是使用索引而不是干净apply:

sapply(seq_len(ncol(z)),function(i) myfunc(z[,i]))
Run Code Online (Sandbox Code Playgroud)

apply将干净的向量放在函数内部,因为它首先将对象转换为矩阵.通过使用[为时间序列对象定义的函数,您确信每次都提取有效的时间序列.