zhiwei li
zhiwei li

Reputation: 1711

can not use Non-standard evaluation in self-define function in r

I want to write a function that extracts some information from gam model. I can do this without self-define function (df is what I wanted):

library(mgcv)
library(tidyverse)
model = gam(mpg ~ cyl, data = mtcars)

result = summary(model)$p.table

estimate = result[2,1]
se = result[2,2]

df = data.frame(estimate = estimate, se = se)
df

Then I wrapped it with a self-define function:

my_gam <- function(y, x, data){
  
  model = gam(y ~ x, data = data)
  
  result = summary(model)$p.table
  
  estimate = result[2,1]
  se = result[2,2]
  
  df = data.frame(estimate = estimate, se = se)
  df
}

But I can not use my function correctly.

my_gam(y = mpg, x = cyl, data = mtcars)

Error in eval(predvars, data, env) : object 'cyl' not found

my_gam(y = 'mpg', x = 'cyl', data = mtcars)

Error in gam(y ~ x, data = data) : Not enough (non-NA) data to do anything meaningful

Is that a way I can get the df just as the first code block when I run my_gam(y = mpg, x = cyl, data = mtcars).

Any help will be highly appreciated!!

Upvotes: 0

Views: 54

Answers (2)

akrun
akrun

Reputation: 886938

We can construct a formula with paste which would be fast

my_gam <- function(y, x, data){
   model <- gam(as.formula(paste(y, "~", x)), data = data)
  result <- summary(model)$p.table
   estimate <- result[2,1]
  se <- result[2,2]
   df <- data.frame(estimate = estimate, se = se)
   df
  }

 my_gam(y = 'mpg', x = 'cyl', data = mtcars)
 #  estimate        se
 #1 -2.87579 0.3224089

Or another option is to pass a formula as argument

my_gam <- function(fmla, data){
   model <- gam(fmla, data = data)
  result <- summary(model)$p.table
   estimate <- result[2,1]
  se <- result[2,2]
   df <- data.frame(estimate = estimate, se = se)
   df
  }

 my_gam(mpg ~ cyl, data = mtcars)
#  estimate        se
# 1 -2.87579 0.3224089
 

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388797

You can use reformulate/as.formula to construct the formula.

library(mgcv)

my_gam <- function(y, x, data){
  model = gam(reformulate(x, y), data = data)
  result = summary(model)$p.table
  estimate = result[2,1]
  se = result[2,2]
  df = data.frame(estimate = estimate, se = se)
  df
}

my_gam(y = 'mpg', x = 'cyl', data = mtcars)
#   estimate     se
#1   -2.876 0.3224

Upvotes: 1

Related Questions