我想加载用于估计的变量的名称形成矩阵。如果矩阵的所有行都包含变量名称,则可以很好地工作。但是,我想测试所有不同组合,如下面的代码中所示。在这里,一些行只包含"。如果一行不包含变量名,则会出现错误。是否有一种从矩阵中加载名称的方法,其中包含空条目?
library("vars") # required for VAR analysis
Data <- data.table(
A=c(1:100),
B=c(2:102),
C=c(3:103)
)
VARIABLES.Matrix <- rbind(
c("A","B","C"),
c("A","B",""),
c("A","",""),
c("A","","C"),
c("","","C"),
c("","B","C")
)
for (i in 1:nrow(VARIABLES.Matrix)){
VARselect(Data[, as.matrix(VARIABLES.Matrix)[i,1:3], with=F], lag.max = 3)
}
# This works fine
VARselect(Data[, as.matrix(VARIABLES.Matrix)[1,1:3], with=F], lag.max = 3)
# This does not work, which is related to ""
VARselect(Data[, as.matrix(VARIABLES.Matrix)[3,1:3], with=F], lag.max = 3)
我的问题是:为什么您需要坚持从矩阵加载变量,为什么您不从列表中加载变量,其元素只是要使用的变量的名称?这样:
library("data.table")
library("vars") # required for VAR analysis
Data <- data.table(
A=c(1:101),
B=c(2:102),
C=c(3:103)
)
VARIABLES.List <- list(
c("A","B","C"),
c("A","B"),
c("A"),
c("A","C"),
c("C"),
c("B","C")
)
for (VARS in VARIABLES.List){
VARselect(Data[, VARS], lag.max = 3)
}
我认为VARIABLES.List
更加简洁,使用。您也可以用lapply
替换for-loop
。
lapply(VARIABLES.List, function(VARS) VARselect(Data[, VARS], lag.max = 3))