不能在R中的自定义函数中使用非标准评估 [英] can not use Non-standard evaluation in self-define function in r

查看:66
本文介绍了不能在R中的自定义函数中使用非标准评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

eval(predvars,data,env)中的错误:找不到对象'cyl'

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

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

gam中的错误(y〜x,data = data):没有足够的(非NA)数据无法做任何有意义的事情

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

这是我运行 my_gam(y = mpg,x = cyl,data = mtcars)时获得第一个代码块的方法.

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).

任何帮助将不胜感激!

推荐答案

您可以使用 reformulate / as.formula 构造公式.

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

这篇关于不能在R中的自定义函数中使用非标准评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆