我正在尝试创建一个优雅的解决方案,可以选择一组数据,然后将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
解决方案欢迎。
答案 0 :(得分:0)
你的功能与你想要的并不太远。我做了一些改变,我相信这就是你想要的:
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"))
可能有更优雅的解决方案,但这就是我想出来的。