以下腳本用於打印具有單位根測試結果的表格。你可以自己嘗試一下代碼。在表格中打印精確的兩個十進制數字?
library(vars)
Canada = data.frame(Canada)
library(urca)
library(stargazer)
library(dplyr)
table_adf = function(DF, ...){
var_list = as.list(unlist(list(...)))
if(length(var_list) == 0){
subset = DF
var_list = as.list(names(DF))
}else{
subset = select_(DF, .dots = var_list)
}
tests = lapply(subset, function(x, y){
out1 = ur.df(x, type = "drift", selectlags = "BIC")
out2 = ur.df(x, type = "trend", selectlags = "BIC")
out3 = ur.pp(x, type = "Z-tau", model = "const", lags = "short")
out4 = ur.pp(x, type = "Z-tau", model = "trend", lags = "short")
out5 = ur.kpss(x, type = "mu", lags = "short")
out6 = ur.kpss(x, type = "tau", lags = "short")
return(list(out1, out2, out3, out4, out5, out6))
})
est_df = lapply(tests, function(x){
data.frame(ADF_constant = x[[1]]@teststat[1],
ADF_trend = x[[2]]@teststat[1],
PP_const = x[[3]]@teststat[1],
PP_trend = x[[4]]@teststat[1],
KPSS_const = x[[5]]@teststat[1],
KPSS_trend = x[[6]]@teststat[1])
})
est_table = do.call(rbind, est_df)
est_table = round(est_table, 2)
critical_vals = data.frame(tests[[1]][[1]]@cval[1,],
tests[[1]][[2]]@cval[1,],
tests[[1]][[3]]@cval[1,],
tests[[1]][[4]]@cval[1,],
tests[[1]][[5]]@cval[1,-1],
tests[[1]][[6]]@cval[1,-1])
est_table[, 1:4] = Map(function(x, y){
ifelse(x < y[1], paste(x, "0.01"),
ifelse(x < y[2], paste(x, "0.05"),
ifelse(x < y[3], paste(x, "0.10"), paste(x, ""))))
}, est_table[, 1:4], critical_vals[, 1:4]) %>% data.frame(row.names = unlist(var_list))
est_table[, 5:6] = Map(function(x, y){
ifelse(x > y[3], paste(x, "0.01"),
ifelse(x > y[2], paste(x, "0.02"),
ifelse(x > y[1], paste(x, "0.05"), paste(x, ""))))
}, est_table[, 5:6], critical_vals[, 5:6]) %>% data.frame(row.names = unlist(var_list))
stargazer(est_table, type = "text", summary = FALSE)
}
table_adf(Canada, "e", "prod", "rw", "U")
輸出表:
=====================================================================
ADF_constant ADF_trend PP_const PP_trend KPSS_const KPSS_trend
---------------------------------------------------------------------
e -0.3 -2.73 0.15 -1.62 2.05 0.01 0.17 0.05
prod -0.11 -2.02 0.26 -1.97 1.66 0.01 0.27 0.01
rw -4.37 0.01 -2.82 -5.62 0.01 -2.81 2.12 0.01 0.43 0.01
U -2.22 -2.47 -1.72 -1.96 0.23 0.14
---------------------------------------------------------------------
正如你可以看到的例子中,第一值顯示爲-0.3
代替-0.30
。我如何調整腳本,使每個測試結果都打印成一個有兩位小數的數字?
你應該在這裏做與原來的問題了一句:https://stackoverflow.com/questions/46634643/r -function到打印表與平穩性試驗結果/ 46637222#46637222。 –