Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify the left side of a formula?

Tags:

r

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 ~ .)
like image 805
Freddy Avatar asked Jun 15 '16 01:06

Freddy


2 Answers

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.

like image 139
Gavin Simpson Avatar answered Nov 01 '22 06:11

Gavin Simpson


response <- 'profit'
mo.fo <- ~ x1 + x2
mo.fo <- as.formula(paste(response, "~ x1+x2"))
mo.fo

profit ~ x1 + x2
like image 35
Hack-R Avatar answered Nov 01 '22 07:11

Hack-R