use*_*065 4 r formula linear-regression
我有一个lm对象,想要用系数提取公式.我知道如何提取没有系数的公式,以及如何在没有公式的情况下获得系数,而不是如何获得例如.y~10 + 1.25b而不是y~b或者是拦截,b等等的表
这是我目前正在使用的代码:
a = c(1, 2, 5)
b = c(12, 15, 20)
model = lm(a~b)
summary(model)
formula = formula(model)
formula
coefficients(model)
Run Code Online (Sandbox Code Playgroud)
我想从上面得到的是y~-5.326 + .51b
谢谢
编辑:在我的实际代码中,我正在使用超过63个预测器和18个不同的模型,所以我想要一些可以在没有太多工作的情况下扩展的东西.
as.formula(
paste0("y ~ ", round(coefficients(model)[1],2), " + ",
paste(sprintf("%.2f * %s",
coefficients(model)[-1],
names(coefficients(model)[-1])),
collapse=" + ")
)
)
# y ~ -5.33 + 0.51 * b
Run Code Online (Sandbox Code Playgroud)
我可以建议编辑lukeA的优秀答案:
as.formula(
paste0("y ~ ", round(coefficients(model)[1],2), "",
paste(sprintf(" %+.2f*%s ",
coefficients(model)[-1],
names(coefficients(model)[-1])),
collapse="")
)
)
Run Code Online (Sandbox Code Playgroud)
这将确保正确打印负系数
假设你用b的负系数着陆,那么输出就是
# y ~ -5.33 + -0.51 * b
Run Code Online (Sandbox Code Playgroud)
代替
# y ~ -5.33 - 0.51 * b
Run Code Online (Sandbox Code Playgroud)