我有一个数据框,我想为每一列拟合一个 mixR 模型并打印绘图。没有使用函数的代码没有任何问题,但是当在函数中调用它时,就发生了错误。我检查了多次,但没有发现任何异常。有什么提示吗?谢谢。
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))
这块代码是正常的,但是函数中的下面的代码返回错误:Error in eval(mc,environment()) : object 'column_names' not find
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")
看起来很奇怪,我花了几个小时调试。
该函数以一种奇怪的方式编写,在将其传递给辅助函数之前,它不会评估
x
参数。此辅助函数无法解析调用环境中的变量。我认为这是一个您可能想要向包作者报告的错误。解决方法是运行
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")
通过此解决方案,您可以欺骗评估以找到正确的
x
值。