不能在r中的自定义函数中使用非标准评估

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

我想编写一个从 gam 模型中提取一些信息的函数。 我可以在没有自定义功能的情况下做到这一点(df 是我想要的):

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

然后我用自定义函数包装了它:

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
}

但是我无法正确使用我的函数。

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

当我 运行 my_gam(y = mpg, x = cyl, data = mtcars).

时,这是我可以获得 df 作为第一个代码块的方法吗

任何帮助将不胜感激!!

您可以使用reformulate/as.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

我们可以用 paste 构造一个公式,这会很快

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

或者另一种选择是将公式作为参数传递

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