我要修改左边的mu.fo
具有存储在 response
中的值的公式多变的。这个想法是获得这样的新公式:profit ~ x1 + x2
但实际上我得到了 response ~ x1 + x2
.
如何使用存储在 response
中的值自动变量?
response <- 'profit'
mu.fo <- ~ x1 + x2
update.formula(mu.fo, response ~ .)
最佳答案
有多种方法可以实现这一点。
一种方法是使用 as.name()
对信息进行编码 "profit"
作为字符串以外的东西,作为 R 名称(或符号)。
response <- as.name("profit")
frm <- as.formula(bquote(.(response) ~ .))
str(frm)
> str(frm)
Class 'formula' language profit ~ .
..- attr(*, ".Environment")=<environment: R_GlobalEnv>
这里
response
是符号/名称 profit
.我们使用 bquote
替换 response
中的东西而不是文字 response
,并将该表达式强制转换为公式。这样,我们最终得到的对象与我们输入 profit ~ .
的对象相同。> all.equal(frm, profit ~ .)
[1] TRUE
如果
"profit"
,这有效也在字符向量中:foo <- c("profit", "loss")
response <- as.name(foo[1])
as.formula(bquote(.(response) ~ .))
response <- as.name(foo[2])
as.formula(bquote(.(response) ~ .))
> foo <- c("profit", "loss")
> response <- as.name(foo[1])
> as.formula(bquote(.(response) ~ .))
profit ~ .
> response <- as.name(foo[2])
> as.formula(bquote(.(response) ~ .))
loss ~ .
另一种方式是
paste()
串在一起或使用 reformulate()
response <- "profit"
f1 <- formula(paste(response, "~ ."))
f2 <- reformulate(".", response = response)
str(f1)
str(f2)
all.equal(f1, f2)
all.equal(frm, f1)
> str(f1)
Class 'formula' language profit ~ .
..- attr(*, ".Environment")=<environment: R_GlobalEnv>
> str(f2)
Class 'formula' language profit ~ .
..- attr(*, ".Environment")=<environment: R_GlobalEnv>
> all.equal(f1, f2)
[1] TRUE
> all.equal(frm, f1)
[1] TRUE
您最终选择哪个实际上取决于您真正在做什么。
关于r - 如何修改公式的左边?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37824625/