Error "object not found" when using "alm()" inside a function but not outside a function

49 views Asked by At

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!
1

There are 1 answers

1
LocoGris On

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!