在MTS对象上使用Apply系列函数 [英] Using Apply family of functions on mts objects

查看:65
本文介绍了在MTS对象上使用Apply系列函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在发送给函数时,在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])
}

现在获取样本山

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆