tags:

views:

93

answers:

2

I am writing a function that takes two variables and separately regresses each of them on a set of controls expressed as a one-sided formula. Right now I'm using the following to make the formula for one of the regressions, but it feels a bit hacked-up:

foo <- function(x, y, controls) {
    cl <- match.call()
    xn <- cl[["x"]]
    xf <- as.formula(paste(xn, deparse(controls)))
}

I'd prefer to do this using update.formula(), but of course update.formula(controls, x ~ .) and update.formula(controls, as.name(x) ~ .) don't work. What should I be doing?

+1  A: 

I am not sure about update.formula(), but I have used the approach you take here of pasting text and converting it via as.formula in the past with success. My reading of help(update.formula) does not make me think you can substitute the left-hand side as you desire.

Lastly, trust the dispatching mechanism. If you object is of type formula, just call update which is preferred over the explicit update.formula.

Dirk Eddelbuettel
+3  A: 

Here's one approach:

right <- ~ a + b + c
left <- ~ y 
left_2 <- substitute(left ~ ., list(left = left[[2]]))

update(right, left_2)

But I think you'll have to either paste text strings together, or use substitute. To the best of my knowledge, there are no functions to create one two sided formula from two one-sided formulas (or similar equivalents).

hadley