1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh, Gosh! It works finally. Thank you so much, MrFlick. I'll definitely report to the author. You're my life saver!
I should have read the package manual more carefully. Really appreciate!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.