Extract Formula From lm with Coefficients (R)

后端 未结 4 1051
迷失自我
迷失自我 2021-01-13 06:43

I have an lm object and want to get the formula extracted with coefficients. I know how to extract the formula without coefficients, and how to get the coefficients without

4条回答
  •  生来不讨喜
    2021-01-13 07:25

    Might I suggest an edit to lukeA's excellent answer:

    as.formula(
      paste0("y ~ ", round(coefficients(model)[1],2), "", 
        paste(sprintf(" %+.2f*%s ", 
                      coefficients(model)[-1],  
                      names(coefficients(model)[-1])), 
              collapse="")
      )
    )
    

    This will make sure that negative coefficients are printed correctly

    Suppose you land up with a negative coefficient for b, then the output will be

    # y ~ -5.33 + -0.51 * b
    

    instead of

    # y ~ -5.33 - 0.51 * b
    

提交回复
热议问题