Search code examples
rfunctionparameter-passingenvironmentgam

Error in is.data.frame(data) : object 'data='' not found


I'm pretty new to r and struggling to write a function: I'm trying to make one that fits a GAM. I found an example for a linear model, that works perfectly fine. However, trying to use the same structure for a GAM throws me an error.

Linear Model:

library(mgcv)
library(ggplot2)
theme_set(theme_bw())
set.seed(100)
dd <- data.frame(x=1:100,y=round(rnorm(100,mean=100),1), z=round(runif(100,1,4),1))
lm(y~x, weights=z, data=dd)$call
lm(formula = y ~ x, data = dd, weights = z)

f2 <- function(f,w,d){
   do.call("lm", list(formula=as.formula(f), weights=as.name(w), data=as.name(d)))
 }
 f2("y~x", "z", "dd")$call
lm(formula = y ~ x, data = dd, weights = z)

and the GAM version

set.seed(100)
dd <- data.frame(x=1:100,y=round(rnorm(100,mean=100),1))
gam(y ~ s(x, k=64, bs='ad'), data = dd, method = 'REML', select = 'TRUE')$call
gam(formula = y ~ s(x, k=64, bs='ad'), data = dd, method = 'REML', select = 'TRUE')

 f2 <- function(f,m,s,d){
    do.call("gam", list(formula=as.formula(f),method=as.name(m),select=as.name(s),data=as.name(d)))
  }

f2("y ~ s(x, k=64, bs='ad')", "method = 'REML'", "select = 'TRUE'", "data = dd")$call

# Error in is.data.frame(data) : object 'data = dd' not found occurs

gam(formula = y ~ s(x, k = 64, bs = "ad"), data = dd)

Solution

  • Call:

    f2 <- function(f, m, s, d){
        do.call("gam", list(formula=as.formula(f),method = "REML",select = s, data = as.name(d)))
    }
    f2("y ~ s(x, k=64, bs='ad')", "REML", TRUE, d = "dd")$call
    

    Result:

    gam(formula = y ~ s(x, k = 64, bs = "ad"), data = dd, method = "REML", 
        select = TRUE)