我正在使用
alm()
包中的 greybox
函数来拟合位置和比例模型。但是,每当我将变量传递给 formula =
的 alm()
参数时,我都会收到错误。这仅发生在函数内部。外部函数可以工作。返回的错误是“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!
这可行,但这是一项肮脏的工作。 我认为这是一个与全球环境或其他相关的问题。如果将 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)
form <<- form
f<-alm(as.formula(form), data = df)
rm(form)
f
}
test_fun(form = test_string, df = df)
#Passing formula to alm() does not work!
在包修复范围错误之前,您可以包装在 do.call 中,由于某种原因,这修复了范围问题:
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!
test_fun2 = function(form, df){
#alm(scaled_meaning ~ short_dis_km, data = x)
do.call(alm,list(as.formula(form),data=df))
}
test_fun2(form = test_string, df=df)
# This one works!