有什么简单的方法可以在 R 中创建公式列表
Is there any simple way to create a list of formula in R
在这里,我想为简单的线性回归、二阶和三阶多项式模型创建一个公式列表。我刚刚做了这个。几个变量可能没问题,但我的数据是很多变量。那么我怎样才能避免使用另一种方法来做同样的事情呢?
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)
在这里,我想为简单的线性回归、二阶和三阶多项式模型创建一个公式列表。我刚刚做了这个。几个变量可能没问题,但我的数据是很多变量。那么我怎样才能避免使用另一种方法来做同样的事情呢?
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)