错误“未找到对象”当使用“alm()”时在函数内部但不在函数外部
我使用 greybox
包中的 alm()
函数来拟合位置和比例模型。但是,每当我将变量传递给 alm()
的 formula =
参数时,我都会收到错误。这仅发生在函数内部。外部函数可以工作。返回的错误是“as.formula(form) 中的错误:找不到对象“form””。下面是一个可重现的示例。有修复的想法吗? 可重现的例子:
library(greybox)
df <- data.frame(x = rnorm(100),
y = rnorm(100))
test_string = "y ~ x"
alm(as.formula(test_string), data = df)
#Passing formula to alm() works!
test_fun = function(form, df){
#alm(scaled_meaning ~ short_dis_km, data = x)
alm(as.formula(form), data = df)
}
test_fun(form = test_string, df = df)
#Passing formula to alm() does not work!
I'm using the alm()
function from the greybox
package to fit a location and scale model. However, I get an error whenever I pass a variable to the formula =
argument of alm()
. This only happens inside functions. Outside functions it work. The error returned is "Error in as.formula(form) : object 'form' not found". Below is a reproducible example. Any ideas for a fix?
Reproducible example:
library(greybox)
df <- data.frame(x = rnorm(100),
y = rnorm(100))
test_string = "y ~ x"
alm(as.formula(test_string), data = df)
#Passing formula to alm() works!
test_fun = function(form, df){
#alm(scaled_meaning ~ short_dis_km, data = x)
alm(as.formula(form), data = df)
}
test_fun(form = test_string, df = df)
#Passing formula to alm() does not work!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可行,但这是一项肮脏的工作。
我认为这是一个与全球环境或其他相关的问题。如果将 form 声明为全局变量,则可以避免此问题。但它并不干净。
This works, but it is dirty work.
I think it is an issue related to GlobalEnvironment or something. If you declare form as a Global Variable you can avoid this problem. But it is not clean.
在包修复范围错误之前,您可以包装在 do.call 中,由于某种原因,这修复了范围问题:
Until the package fixes the scoping error, you can wrap in do.call, for some reason this fixes the scoping issue: