Search code examples
rfunctionerror-handlingstatisticsfunction-call

R function call in error using mixR package


I have a dataframe and I want to fit a mixR model for each column and print the plot. The code without using function without any problem, but when it was called in a function, an error happened. I checked them multiple times, but not able to find any abnormality. Any hint? Thanks.

library(mixR)

twins = data.frame(
  apple = rnorm(100),
  orange = rnorm(100, mean = 2),
  banana = rnorm(100, mean = 5),
  peach = rnorm(100, mean = 10)
)
fit = mixR::mixfit(twins[["apple"]], ncomp = 2)
print(plot(fit, what = "after_stat(density)", title = paste0("Gaussian mixR Model ", "apple"), cex.main = 20))

The chunk of code is normal, but the code below in a function returns an error:Error in eval(mc, environment()) : object 'column_names' not found

mixR_plot = function(data, column_names){
  fit = mixR::mixfit(data[[column_names]], ncomp = 2)
  print(plot(fit, what = "after_stat(density)", title = paste0("Gaussian mixR Model", column_names), cex.main = 20))
}

mixR_plot(twins, "apple")

It seems quite weird, I have spent hours for debugging.


Solution

  • The function is written in a weird way where it doesn't evaluate the x parameters before passing it off to a helper function. This helper function can't resolved the variables in the calling environment. I'd consider this a bug you might want to report to the package author. A work around is to run

    mixR_plot = function(data, column_names){
      x <- data[[column_names]] # Must be named "x"
      fit = mixR::mixfit(x, ncomp = 2)
      print(plot(fit, what = "after_stat(density)", 
          title = paste0("Gaussian mixR Model", column_names), cex.main = 20))
    }
    
    mixR_plot(twins, "apple")
    

    With this work around, you can trick the evaulation to find the right x value.