vector of variable names in R

后端 未结 3 1421
鱼传尺愫
鱼传尺愫 2020-12-09 12:50

I\'d like to create a function that automatically generates uni and multivariate regression analyses, but I\'m not able to figure out how I can specify **variables in vector

3条回答
  •  青春惊慌失措
    2020-12-09 13:46

    get() is what you're looking for :

    summary(get(k[1]))
    

    edit : get() is not what you're looking for, it's list(). get() could be useful too though.

    If you're looking for automatic generation of regression analyses, you might actually benefit from using eval(), although every R-programmer will warn you about using eval() unless you know very well what you're doing. Please read the help files about eval() and parse() very carefully before you use them.

    An example :

    d <- data.frame(
      var1 = rnorm(1000),
      var2 = rpois(1000,4),
      var3 = sample(letters[1:3],1000,replace=T)
    )
    
    vars <- names(d)
    
    auto.lm <- function(d,dep,indep){
          expr <- paste(
              "out <- lm(",
              dep,
              "~",
              paste(indep,collapse="*"),
              ",data=d)"
          )
          eval(parse(text=expr))
          return(out)
    }
    
    auto.lm(d,vars[1],vars[2:3])
    

提交回复
热议问题