0

I want to load the names of variables used for estimations form a matrix. This works quite well if all rows of the matrix contain variable names. However, I want to test all different combinations like shown in the code below. Here some rows only contain "". If one row does not contain a variable name I got an error. Is there a method to load names from a matrix which contains empty entry’s?

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)
4

1 回答 1

0

My problem is: why do you need to stick to loading variables from matrix, why do you not load variables from a list, whose elements are just the names of variables you want to use? Like this:

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)
}

I think the VARIABLES.List is more concise and elegant to use. And you may also replace the for-loop with lapply.

lapply(VARIABLES.List, function(VARS) VARselect(Data[, VARS], lag.max = 3))
于 2017-06-04T00:06:50.200 回答