在 mts 对象上使用 Apply 系列函数 [英] Using Apply family of functions on mts objects
问题描述
在 mts 对象上使用 apply(或 sapply)会在发送到函数时删除其时间序列属性.我应该如何在 mts 对象中的每个时间序列上应用相同的函数(带有 ts 输入和 ts 输出)并返回它(最好是 mts)[我的意思是除了使用 for 循环之外]?
Using apply (or sapply) on an mts object removes its time series properties when sending to function. How should I apply same function (with ts input and ts output) on each of times series in an mts object and return it (preferably as mts) [I mean besides using for loops]?
例如假设我编写了一个返回时间序列趋势的函数(使用 stl)
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])
}
现在是一个示例 mts
Now for a 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 correct:
myfunc(z[,1]) # works correctly, returns the trend of first series
我的函数不是为多个时间序列设计的,所以:
My function is not designed for multiple time series so:
myfunc(z) # will not work returning the error below
Error in stl(x, "per") : only univariate series are allowed
在 mts 对象上使用 apply 将每个时间序列作为向量发送,而不保留其时间序列属性 (tsp):
Using apply on the mts object send each of the time series as a vector, not preserving its time series properties (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
推荐答案
解决这个问题的一个简单方法是使用索引而不是干净的 apply
:
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
将干净的向量放入函数中,因为它首先将对象转换为矩阵.通过使用为时间序列对象定义的 [
函数,您可以确保每次都提取有效的时间序列.
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.
这篇关于在 mts 对象上使用 Apply 系列函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!