Reputation: 182
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!
Upvotes: 0
Views: 66
Reputation: 555
Until the package fixes the scoping error, you can wrap in do.call, for some reason this fixes the scoping issue:
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!
Upvotes: 0
Reputation: 4480
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.
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!
Upvotes: 1