有什么简单的方法可以在R中创建公式列表

时间:2019-05-26 14:30:59

标签: r list regression formula

在这里,我想为简单的线性回归,二阶和三阶多项式模型创建一个公式列表。我就是这么做的可以使用几个变量,但是我的数据是很多变量。那么如何避免使用另一种方法来完成相同工作的工作量过大?

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

谢谢!

1 个答案:

答案 0 :(得分:3)

定义自变量和公式的格式,由此可以得到公式字符串。由于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)
相关问题