Search code examples
rformulamgcv

Add a string as a formula with defined function


I want to define a function when I input a string as covariate the function will put my string on the specific location and transform it as a formula. I know my code is incorrect but I do not know how to write it.

What I want is when I type covars <- "+s(time,bs= 'cr',fx=TRUE,k=7)" the function will add covarsto the formula like this gam.model <- gam(cvd ~ pm10 +s(time,bs= 'cr',fx=TRUE,k=7), data = chicagoNMMAPS , family =poisson, na.rm=T)

library(dlnm) # use chicagoNMMAPS data
library(mgcv)
# define myfun
myfun <- function(covars){
  covars <- covars
  gam.model <- gam(cvd ~ pm10 + covars, data = chicagoNMMAPS , family =poisson, na.rm=T)
  summary(gam.model)

}

myfun("+s(time,bs= 'cr',fx=TRUE,k=7)")

myfun should do this :

gam.model <- gam(cvd ~ pm10 + covars, data = chicagoNMMAPS , family =poisson, na.rm=T)

Solution

  • Are You looking for this, not sure but try this as.formula with paste0:

    myfunc_formula <- function(covars){
    return(as.formula(paste0('cvd ~ pm10 ', covars)))
    }
    

    we can later use this input to gam(myfunc_formula(covars), data = chicagoNMMAPS , family =poisson, na.rm=T),

    ## In case someone wants to return the summary of given gam model
    myfunc_formula_v1 <- function(covars){
    gam1 <- gam(as.formula(paste0('cvd ~ pm10 ', covars)), data = chicagoNMMAPS , family =poisson, na.rm=TRUE)
    return(summary(gam1))
    }
    

    Also we can make it flexible, by providing parameters for input like target variable name etc.

    for example another version could be:

    myfunc_formula_v2 <- function(covars, target='cvd'){
       return(as.formula(paste0(target, ' ~ pm10 ', covars)))
    }
    

    Output:

    > myfunc_formula(covars)
    cvd ~ pm10 + s(time, bs = "cr", fx = TRUE, k = 7)
    

    given covars = "+s(time,bs= 'cr',fx=TRUE,k=7)"