2

When contained inside a custom function, RVAideMemoire::Anova.clm does not find the 'df1' data object that was passed to ordinal::clm (It would seem because it searches for 'df1' in the global environment):

library(ordinal)
library(RVAideMemoire)

set.seed(1)
df <- data.frame(x = factor(sample(1:2, 100, replace=TRUE)), 
                 y = factor(sample(1:5, 100, replace=TRUE), ordered=TRUE))

clm_function <- function(dv, gv, df1){
  model <- ordinal::clm(as.formula(paste0(dv, " ~ ", gv)), data = df1)
  result <- RVAideMemoire::Anova.clm(model, type = "II") 
  return(result)
}

clm_function(dv = "y", gv = "x", df1 = df)

Error in is.data.frame(data) : object 'df1' not found

One can sidestep this error by using assign to put 'df1' in the global environment temporarily:

clm_function_alt <- function(dv, gv, df1){
  assign("df1", df1, envir=globalenv()) # ASSIGN HERE
  model <- ordinal::clm(as.formula(paste0(dv, " ~ ", gv)), data = df1)
  result <- RVAideMemoire::Anova.clm(model, type = "II") 
  rm(df1, pos = 1) # REMOVE HERE
  return(result)
}

clm_function_alt(dv = "y", gv = "x", df1 = df)

LyzandeR’s answer in this post implies that assigning ‘df1’ to the global environment outside the function is the way to go.

But I am wondering if there something potentially problematic with using assign from inside a function, like I have shown?

If so, is there a way to instruct RVAideMemoire::Anova.clm to search for ‘df1’ in the execution environment?

xilliam
  • 2,074
  • 2
  • 15
  • 27

0 Answers0