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'
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)
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()
}
Kludgy but it works:
form1 <- as.formula("hi ~ lo + mid")
form2 <- as.formula("blue ~ red + green")
form2[[3]] <- form1[[3]]
> form2
blue ~ lo + mid
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