Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading