简体   繁体   中英

Dynamic variable name R

I have already read similar questions regarding the assign command. But it doesnt work for me.

Here is my code:

masums <- function(var) {
    lags <- var$p                    # number of lags in VAR
    eqn  <- length(var$varresult)    # number of equations in VAR
    dep  <- names(var$varresult)     # names of dependent variables

    for(i in 1:eqn) # compute coefficient matrices
        d <- dep[i]
        x <- paste("var$varresult$",d,"$coefficients",sep="")
        y <- as.matrix(GET THE VALUE OF "x" e.g. var$varresult$d$coefficients) # d="gap" for i=1
    }
    return(y)
}

Example: For i=1 d would have the value "gap", therefore I want the value of var$varresult$gap$coefficients.

var$varresult consists of elements of class "lm". Maybe the solution is easy and I am just to stressed to see it. Hope someone can help.

Edit: For a small example dataset:

library(vars)
y <- c(100*rnorm(100))
x <- seq(1,100,1)

vardata <- cbind(x,y)
var1    <- VAR(vardata,p=4,type="const")
var1$varresult$x$coefficients

Martin

paste to construct a nested variable access in a string is the completely wrong approach.

What you are missing is the fact that x$y can also be written as x$['y'] (or x$[['y']] , depending whether you want a single value in a list, or a column in a data.frame), and here 'y' is a string . So you can write this:

y <- as.matrix(var$varresult[[d]]$coefficients)

(assuming var$varresult is a list)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM