Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass the right-hand side of a formula to another formula?

Tags:

r

I would like to pass the right-hand side of a formula to an R function which then "adds" the left-hand side of the formula and calls gam(). I would like to achieve this without ugly as.formula() constructions etc.

I got stuck in the following minimal example, do you know what went wrong?

require(mgcv)
set.seed(0) ## set.seed(1)
gamEx1 <- gamSim(1, n=400, dist="normal", scale=2) ## simulate some data
str(gamEx1) ## display structure

## calling gam() and passing the right-hand side of a formula
gamFitter <- function(formula.RHS, data, ...){
    z <- 2*data$y + data$f0 # some given values
    gam(z ~ formula.RHS, data=data, ...) # call gam()
}

## call the function with the right-hand side of a formula
gamFitter(formula.RHS=~s(x0)+s(x1)+s(x2)+s(x3), data=gamEx1)

Error in model.frame.default(formula = z ~ formula.RHS, data = data,
                             drop.unused.levels = TRUE) :
  invalid type (language) for variable 'formula.RHS'
like image 452
Marius Hofert Avatar asked Apr 14 '12 15:04

Marius Hofert


3 Answers

It seems that you should use the built in functionality of R, namely update.formula, no need to write a new function:

> form <- ~s(x0)+s(x1)+s(x2)+s(x3)
> form
~s(x0)+s(x1)+s(x2)+s(x3)
> update.formula(form, z ~ .)
z ~ s(x0) + s(x1) + s(x2) + s(x3)
like image 95
Derek McCrae Norton Avatar answered Oct 26 '22 15:10

Derek McCrae Norton


Here's a version building upon @gsk3's idea:

changeLHS <- function(formula, lhs) {
   if (length(formula) == 2) {
     formula[[3]] <- formula[[2]]
   }
   formula[[2]] <- substitute(lhs)
   formula
}

changeLHS(a~b+c, z+w)  # z + w ~ b + c
changeLHS(~b+c, z+w)   # z + w ~ b + c

So, your code becomes:

gamFitter <- function(formula.RHS, data, ...){
  frm <- changeLHS(formula.RHS, 2*y + f0)
  gam(frm, data=data, ...) # call gam()
}
like image 33
Tommy Avatar answered Oct 26 '22 15:10

Tommy


Kludgy but it works:

form1 <- as.formula("hi ~ lo + mid")
form2 <- as.formula("blue ~ red + green")
form2[[3]] <- form1[[3]]
> form2
blue ~ lo + mid
like image 29
Ari B. Friedman Avatar answered Oct 26 '22 16:10

Ari B. Friedman