本文介绍了不能在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)
my_gam(y = 'mpg', x = 'cyl', data = mtcars)
这是我运行 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中的自定义函数中使用非标准评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!