【问题标题】:avoid repeatedly writing model formula when fitting a number of linear regression models避免在拟合多个线性回归模型时重复编写模型公式
【发布时间】:2019-02-13 00:50:07
【问题描述】:

我想在 R 中运行一些类似的线性回归模型,例如

lm(y ~ x1 + x2 + x3 + x4 + x5, data = df)
lm(y ~ x1 + x2 + x3 + x4 + x5 + x6, data = df)
lm(y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7, data = df)

如何将其中的一部分分配给“基本”公式,以避免重复多次?这将是基础:

y ~ x1 + x2 + x3 + x4 + x5

那我该怎么做类似以下的事情(显然不起作用)?

lm(base + x6, data = df)

在 Stack Overflow 上搜索,我意识到我可以制作一个只包含感兴趣变量的数据框,并使用 . 来缩短模型公式,但我想知道是否可以避免这种情况。

【问题讨论】:

  • 你可能会发现step很有用

标签: r regression formula linear-regression lm


【解决方案1】:

您可以使用update.formula 更新模型公式。例如:

base <- y ~ x1 + x2 + x3 + x4 + x5
update.formula(base, . ~ . + x6)
#y ~ x1 + x2 + x3 + x4 + x5 + x6

如果您想提供新的变量名作为字符,这里是一个字符串版本:

## `deparse` damp a model formula to a string
formula(paste(deparse(base), "x6", sep = " + "))

其实你甚至可以直接更新你的模型

fit <- lm(base, dat); update.default(fit, . ~ . + x6)

这种更新整个模型的想法效果最好。我的情况只需要update()

我写了update.defaultupdate.formula,以便您知道在为文档执行? 时要查找什么函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 1970-01-01
    • 2016-09-03
    • 2022-07-06
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    相关资源
    最近更新 更多