gpt4 book ai didi

r - 有没有简单的方法可以在 R 中创建公式列表

转载 作者:行者123 更新时间:2023-12-02 03:15:26 26 4
gpt4 key购买 nike

在这里,我想创建一个简单线性回归、二阶和三阶多项式模型的公式列表。我刚刚做了这个。对于几个变量来说可能没问题,但我的数据有很多变量。那么我怎样才能避免使用另一种方法来做同样的事情而导致工作负担过重呢?

ind1.lm <- lm(dep ~ ind1, data = df)
ind1.qd <- lm(dep ~ poly(ind1, 2, raw = TRUE), data = df)
ind1.cb <- lm(dep ~ poly(ind1, 3, raw = TRUE), data = df)

ind2.lm <- lm(dep ~ ind2, data = datAll)
ind2.qd <- lm(dep ~ poly(ind2, 2, raw = TRUE), data = df)
ind2.cb <- lm(dep ~ poly(ind2, 3, raw = TRUE), data = df)

ind3.lm <- lm(dep ~ ind3, data = df)
ind3.qd <- lm(dep ~ poly(ind3, 2, raw = TRUE), data = df)
ind3.cb <- lm(dep ~ poly(ind3, 3, raw = TRUE), data = df)

formula.list <- list(as.formula(ind1.lm), as.formula(ind1.qd),
as.formula(ind1.cb), as.formula(ind2.lm), as.formula(ind2.qd),
as.formula(ind2.cb), as.formula(ind3.lm), as.formula(ind3.qd),
as.formula(ind3.cb))

formula.list

提前致谢!

最佳答案

定义自变量和公式的格式,从中我们可以得到公式字符串。由于 lm 接受字符串作为公式,因此我们可以应用该字符串,给出名称为公式的 lm 对象列表。

ind <- c("ind1", "ind2", "ind3")
fmt <- c("dep ~ %s",
"dep ~ poly(%s, 2, raw=TRUE)",
"dep ~ poly(%s, 3, raw=TRUE)")

fo.strings <- c(outer(fmt, ind, sprintf))

sapply(fo.strings, lm, data = df, simplify = FALSE)

对SO的问题应该包括可重现的代码,问题中省略了df,但我们可以使用内置的anscombe数据框架来运行它,如下所示:

fmt <- c("y1~ %s", 
"y1~ poly(%s, 2, raw=TRUE)",
"y1 ~ poly(%s, 2, raw=TRUE)")
ind <- c("x1", "x2", "x3")
fo.strings <- c(outer(fmt, ind, sprintf))
sapply(fo.strings, lm, data = anscombe, simplify = FALSE)

关于r - 有没有简单的方法可以在 R 中创建公式列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56314413/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com