[英]R function to print table with stationarity test results
我正在嘗試創建一個優雅的解決方案,該解決方案能夠選擇一組數據,然后將Augmented Dickey-Fuller測試結果及其臨界值打印到表中。
我生成了以下示例代碼來獲取所需的數據:
library(urca)
data(Canada)
Canada
data.dft <- ur.df(Canada[, "e"], lags=3, type='drift')
data.df <- ur.df(Canada[, "e"], lags=3, type='trend')
summary(data.dfc)
summary(data.dft)
所需的輸出表:
T-test(drift), 1%, 5%, 10%, T-test(trend), 1%, 5%, 10%
0.4964 -3.51 -2.89 -2.58 -1.9664 -4.04 -3.45 -3.15
嘗試過:
stationarity = function(df, x){
for (i in x){
out1 = ur.df(df.i[,1], type = "drift", selectlags = "BIC")
out2 = ur.df(df.i[,1], type = "trend", selectlags = "BIC")
est_df = cbind(out1@teststat[1],
out1@cval[1,1],
out1@cval[1,2],
out1@cval[1,3],
out2@teststat[1],
out2@cval[1,1],
out2@cval[1,2],
out2@cval[1,3])
print(est_df)
}
}
stationarity(Canada, c("e","prod","RW"))
但是,這不起作用:
“ as.matrix(y)中的錯誤:找不到對象'df.i”。
知道如何正確編寫甚至改進該功能嗎? 如果可能的話,我想直接為ur.pp
測試添加相應的結果。 歡迎使用dplyr
解決方案。
您的功能距離您想要的不太遠。 我進行了一些更改,我相信這是您想要的:
library(urca)
library(vars)
# Load data
data(Canada)
# Function
stationarity <- function(df, x){
# Define empty object
df <- NULL
# The way to write "i in ..."
for (i in 1 : length(x)){
# We change column names as x[1] = "e" and so on
out1 <- ur.df(Canada[,x[i]], type = "drift", selectlags = "BIC")
out2 <- ur.df(Canada[,x[i]], type = "trend", selectlags = "BIC")
# rbind will collect rows after they are combined for each x[i]
df <- rbind(df,
# cbind will work on inner part, when you combine
# the 8 resulting numbers for current x[i]
cbind(out1@teststat[1],
out1@cval[1,1],
out1@cval[1,2],
out1@cval[1,3],
out2@teststat[1],
out2@cval[1,1],
out2@cval[1,2],
out2@cval[1,3]))
}
# assign column names
colnames(df) <- c("T-test(drift)", "1%", "5%", "10%",
"T-test(trend)", "1%", "5%", "10%")
# assign row names
rownames(df) <- x
# result
print(df)
}
stationarity(Canada, c("e","prod","rw"))
也許有更優雅的解決方案,但這就是我想出的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.