I want to modify the left side of the mu.fo
formula with the value stored in the response
variable. The idea is to obtain a new formula like this: profit ~ x1 + x2
but actually I obtain response ~ x1 + x2
.
How can I use the value stored in response
variable automatically?
response <- 'profit'
mu.fo <- ~ x1 + x2
update.formula(mu.fo, response ~ .)
There are a number of ways to achieve this.
One way is to use as.name()
to encode the information "profit"
as something other than a character string, as an R name (or symbol).
response <- as.name("profit")
frm <- as.formula(bquote(.(response) ~ .))
str(frm)
> str(frm)
Class 'formula' language profit ~ .
..- attr(*, ".Environment")=<environment: R_GlobalEnv>
Here response
is the symbol/name profit
. We use bquote
to substitute in the thing in response
rather than a literal response
, and coerce that expression to a formula. This way we end up with the same object as if we'd entered profit ~ .
> all.equal(frm, profit ~ .)
[1] TRUE
This works if "profit"
is in a character vector too:
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 ~ .
The other way is to paste()
strings together or use 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
Which you end up choosing will really depend on what it is that you are really doing.
response <- 'profit'
mo.fo <- ~ x1 + x2
mo.fo <- as.formula(paste(response, "~ x1+x2"))
mo.fo
profit ~ x1 + x2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With