簡體   English   中英

在mts對象上使用Apply系列函數

[英]Using Apply family of functions on mts objects

在mts對象上使用apply(或sapply)會在發送到函數時刪除其時間序列屬性。 我應該如何在mts對象的每個時間序列上應用相同的函數(使用ts輸入和ts輸出)並返回它(最好是mts)[我的意思是除了使用for循環]?

例如,假設我編寫了一個返回時間序列趨勢的函數(使用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

解決這個問題的一個簡單方法是使用索引而不是干凈的apply

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

apply將清除向量放在函數內部,因為它首先將對象轉換為矩陣。 通過使用[為時間序列對象定義的函數,您確定每次都提取有效的時間序列。

我更改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) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM