Strings as variable references in R

前端 未结 2 432
小蘑菇
小蘑菇 2020-12-30 09:05

R newbie question here. I have a list called dbdata. Normally I use it like this:

myresults <- rlm(V001 ~ V002+V003, data=dbdata)


        
相关标签:
2条回答
  • 2020-12-30 09:30

    One solution is to build the formula up using paste() and convert it to a formula:

    > ## your example plus some dummy data
    > var1 <- "V001"
    > var2 <- "V002"
    > var3 <- "V003"
    > dat <- data.frame(V001 = runif(10), V002 = runif(10), V003 = runif(10))
    > f <- formula(paste(var1, "~", var2, "+", var3))
    

    Now we can look at f

    > f
    V001 ~ V002 + V003
    > class(f)
    [1] "formula"
    

    and it really is a formula. We can now pass this into rlm() as the first argument:

    > require(MASS)
    > mod <- rlm(f, data = dat)
    > mod
    Call:
    rlm(formula = f, data = dat)
    Converged in 8 iterations
    
    Coefficients:
    (Intercept)        V002        V003 
      0.2725538  -0.1281576   0.1617250 
    
    Degrees of freedom: 10 total; 7 residual
    Scale estimate: 0.251
    

    HTH

    0 讨论(0)
  • 2020-12-30 09:32

    You can create formulas based on strings with the reformulate function:

    form <- reformulate(c(var2, var3), response = var1)
    # V001 ~ V002 + V003
    
    myresults <- rlm(form, data = dbdata)
    
    0 讨论(0)
提交回复
热议问题