在mts对象上使用apply (或sapply)会在发送到function时删除其时间序列属性。除了使用for循环之外,我应该如何在mts对象中的每个时间序列上应用相同的函数(具有ts输入和ts输出)并返回它(最好是作为mts
例如,假设我编写了一个函数来返回时间序列的趋势(使用stl)
myfunc <- function(x) {
return(stl(x,"per")$time.series[,2])
}现在来看一个示例mts
z <- ts(matrix(rnorm(90), 30, 3), start=c(1961, 1), frequency=4)
class(z)仅发送一个时间序列即可正常工作:
myfunc(z[,1]) # works correctly, returns the trend of first series我的函数不是为多个时间序列设计的,所以:
myfunc(z) # will not work returning the error below
Error in stl(x, "per") : only univariate series are allowed在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发布于 2012-11-27 20:44:57
解决这个问题的一个简单方法是使用索引,而不是干净的apply:
sapply(seq_len(ncol(z)),function(i) myfunc(z[,i]))apply将干净的向量放在函数中,因为它首先将对象转换为矩阵。通过使用为时间序列对象定义的[函数,您可以确保每次提取一个有效的时间序列。
发布于 2012-11-27 20:42:18
我修改myfunc来检查它是否有一个ts对象作为参数x。
如果x不是ts,则将其转换为ts对象,因为stl需要此参数类型。
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) https://stackoverflow.com/questions/13583817
复制相似问题