相关疑难解决方法(0)

以编程方式构建公式而不使用字符串

为了举例,考虑R中的基本回归模型:

form1 <- Petal.Length ~ Sepal.Length + Sepal.Width
fit1 <- lm(form1, iris)
Run Code Online (Sandbox Code Playgroud)

(我向在这里发帖的任何植物学家致歉.)

为了添加二次和交互项,我知道三种方法:

1)老式的方式

一次输入一个条款:

form2 <- . ~ Sepal.Length*Sepal.Width + I(Sepal.Length^2) + I(Sepal.Width^2)
fit2 <- update(fit1, form2)
Run Code Online (Sandbox Code Playgroud)

这不会扩展到小公式之外,您无法使用它进行编程.

2)丑陋的方式

字符串操作:

vars <- attr(terms(form1), "term.labels")
squared_terms <- sprintf("I(%s^2)", vars)
inter_terms <- combn(vars, 2, paste, collapse = "*")
form2 <- reformulate(c(inter_terms, squared_terms), ".")
Run Code Online (Sandbox Code Playgroud)

这可以扩展,但它不是真正可编程的,因为函数本身需要进行硬编码.

3)"后门"

直接操作数据

library(lazyeval)
library(dplyr)

square <- function (v) interp(~ I(v1^2), v1 = as.name(v))
inter <- function(v) interp(~ v1*v2, v1 = as.name(v[1]), v2 = as.name(v[2]))

vars <- …
Run Code Online (Sandbox Code Playgroud)

string r

3
推荐指数
1
解决办法
466
查看次数

标签 统计

r ×1

string ×1