Explicit formula used in linear regression

前端 未结 1 1329
臣服心动
臣服心动 2021-02-06 15:36

I have a list of formulas, and I use lapply and lm to create a list of regression models. However, when I look at the call component of ea

相关标签:
1条回答
  • 2021-02-06 16:15

    You can do some simple computing on the language using bquote to construct your call.

     temp_fm_list = lapply(temp_formula_list, function(x) {
      lmc <- bquote( lm(data = mtcars, formula = .(x)))
      eval(lmc)                                                      
      })
    temp_fm_list
    # Call:
    #   lm(formula = hp ~ 1, data = mtcars)
    # 
    # Coefficients:
    #   (Intercept)  
    # 146.7  
    # 
    # 
    # [[2]]
    # 
    # Call:
    #   lm(formula = hp ~ cyl, data = mtcars)
    # 
    # Coefficients:
    #   (Intercept)          cyl  
    # -51.05        31.96  
    

    Note that

    function(x) do.call('lm', list(formula = x, data = quote(mtcars))
    

    Would also work


    Other approaches....

    Even with your original call you can recreate the formula from the terms object associated with the model

    eg

    x <- hp ~ cyl
    
    lmo <- lm(formula = x, data = mtcars)
    
    formula(lmo)
    ## hp ~ cyl
    
    lmo$call 
    
    
    # lm(formula = x, data = mtcars)
    

    You can mess with this call object if you wish (although this is rather dangerous practice)

    # for example
    
    lmo$call$formula <- x
    lmo$call 
    ##  lm(formula = hp ~ cyl, data = mtcars)
    
    ## however you can create rubbish here too
    lmo$call$formula <- 'complete garbage'
    lmo$call 
    ## lm(formula = "complete garbage", data = mtcars)
    
    # but, being careful, you could use it appropriately
    temp_fm_list = lapply(temp_formula_list, function(x) {
      oo <- lm(data = mtcars, formula = x)
      oo$call$formula <-x
      oo
    })
    
    temp_fm_list
    # Call:
    #   lm(formula = hp ~ 1, data = mtcars)
    # 
    # Coefficients:
    #   (Intercept)  
    # 146.7  
    # 
    # 
    # [[2]]
    # 
    # Call:
    #   lm(formula = hp ~ cyl, data = mtcars)
    # 
    # Coefficients:
    #   (Intercept)          cyl  
    # -51.05        31.96  
    
    0 讨论(0)
提交回复
热议问题