David Z
David Z

Reputation: 7061

How to replace the dependent variable in a formula?

Suppose I have an R formula such that:

fm <- formula(y~x1+x2+x1:x2)

And a set of new response outcomes, y1, y2, y3. How could I replace the y in the formula fm through a for loop?

for (newy in c(y1,y2,y3)){
    newfm=formula(...)
}

Upvotes: 3

Views: 233

Answers (2)

bartektartanus
bartektartanus

Reputation: 16080

Or try this:

for (i in 1:3) {
    as.formula(paste0("y",i,"~x1+x2+x1:x2"))
}

Upvotes: 1

Ben Bolker
Ben Bolker

Reputation: 226871

How about:

fm <- formula(y~x1+x2+x1:x2)
for (newy in c("y1","y2","y3")){
    newfm <- reformulate(deparse(fm[[3]]),response=newy)
    print(newfm)
}
## y1 ~ x1 + x2 + x1:x2
## y2 ~ x1 + x2 + x1:x2
## y3 ~ x1 + x2 + x1:x2

Handling formulas as formulas is admittedly a little tricky -- it's actually easier to handle them as characters and then use reformulate or as.formula.

It would be interesting but considerably trickier to do this in the way suggested by the OP, using symbols rather than characters in the for loop -- i.e. for (newy in c(y1,y2,y3)) because the symbols would somehow have to be intercepted before R tried to evaluate them (and threw an error). I can't see how to make any construction of the form

for (newy in c(y1,y2,y3)) {
    ...
}

work, because R will try to evaluate c(y1,y2,y3) before it enters the for loop ...

Upvotes: 7

Related Questions