隨着lapply
可以在導致 acf
系列所選滯後值的每一列操作rollapply
功能。然後我們使用Reduce
來結合上述步驟的結果。
我已經使用PerformanceAnalytics
包的數據集edhec
這個演示。您 可以相應地更改width
參數。
library("PerformanceAnalytics")
#load test dataset
data(edhec,package="PerformanceAnalytics")
#select subset with fewer columns
edhec_sub = edhec[,1:5]
fn_lag_ACF = function(lagValue = x) {
#for width as 1 year calculate acf for input lagValue for each column
acfList = lapply(edhec_sub,function(x) {
TS = rollapply(x, width = 12,
FUN = function(z) acf(z,na.action=na.pass,lag.max= lagValue,plot=FALSE)$acf[lagValue],
by.column = FALSE, align = "right")
colnames(TS) = colnames(x)
return(TS)
})
#combine acf output for all columns from above step
acfMerge = Reduce(function(x,y) merge.xts(x,y), acfList)
return(acfMerge)
}
#test with lagValue = 2
lag2DF = fn_lag_ACF(lagValue = 2)
輸出:
head(lag2DF,15)
# Convertible.Arbitrage CTA.Global Distressed.Securities Emerging.Markets
#1997-01-31 NA NA NA NA
#1997-02-28 NA NA NA NA
#1997-03-31 NA NA NA NA
#1997-04-30 NA NA NA NA
#1997-05-31 NA NA NA NA
#1997-06-30 NA NA NA NA
#1997-07-31 NA NA NA NA
#1997-08-31 NA NA NA NA
#1997-09-30 NA NA NA NA
#1997-10-31 NA NA NA NA
#1997-11-30 NA NA NA NA
#1997-12-31 0.5560540 -0.3010264 0.02908761 0.3305791
#1998-01-31 0.5055951 -0.4245876 0.04278214 0.1761287
#1998-02-28 0.5195872 -0.4298767 0.01375580 0.1605579
#1998-03-31 0.5070003 -0.4656213 -0.04519778 0.2061610
# Equity.Market.Neutral
#1997-01-31 NA
#1997-02-28 NA
#1997-03-31 NA
#1997-04-30 NA
#1997-05-31 NA
#1997-06-30 NA
#1997-07-31 NA
#1997-08-31 NA
#1997-09-30 NA
#1997-10-31 NA
#1997-11-30 NA
#1997-12-31 -0.11842164
#1998-01-31 -0.05986578
#1998-02-28 -0.09663855
#1998-03-31 -0.09680819
你能在 「他們沒有工作」 細說。爲了讓我們就此問題提供建議,請使用[最低可重現的示例]更新您的帖子(http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)幫幫我。 – OdeToMyFiddle
我用一個例子編輯了原文。 – lapally