维护dynConfiR包时stat_density_2d报错:MASS包依赖问题求解
dynConfiR包ggplot2更新后MASS依赖问题解决
问题概述
维护dynConfiR包时,ggplot2近期更新后出现随机错误:调用stat_density_2d时提示需要MASS包。该错误在rhub检查中复现,但本地及全新环境无法复现。已在DESCRIPTION的Imports中添加MASS依赖,但问题仍存在。
数据示例
相关数据结构:
> head(two_samples) rt response conf variance 1 2.126847 2 2.5466114 low 2 8.987416 2 0.1823433 low 3 2.171899 1 0.7413825 low 4 2.377217 1 1.3632219 low 5 1.606438 1 0.8723695 low 6 4.752876 2 0.2397163 low
生成测试数据的代码:
two_samples <- data.frame(rt = exp(rnorm(1000, 0, 0.1)), conf = rnorm(1000, 0, 2), variance = rep(c("low", "high"), 500), response = rep(c(1, 2), each=500))
报错代码
ggplot(two_samples, aes(x = rt, y = conf)) + stat_density_2d(aes(fill = after_stat(density)), geom = "raster", contour = FALSE) + facet_grid(cols = vars(variance), rows = vars(response), labeller = "label_both")
错误信息
Loading required package: ggplot2 Error in `stat_density_2d()`: ! Problem while computing stat. ℹ Error occurred in the 1st layer. Caused by error in `compute_layer()`: ! The package "MASS" is required for calculating 2D density. Backtrace: ▆ 1. ├─base (local) `<fn>`(x) 2. ├─ggplot2 (local) `print.ggplot2::ggplot`(x) 3. │ ├─ggplot2::ggplot_build(x) 4. │ └─ggplot2 (local) `ggplot_build.ggplot2::ggplot`(x) 5. │ └─ggplot2:::by_layer(...) 6. │ ├─rlang::try_fetch(...) 7. │ │ ├─base::tryCatch(...) 8. │ │ │ └─base (local) tryCatchList(expr, classes, parentenv, handlers) 9. │ │ │ └─base (local) tryCatchOne(expr, names, parentenv, handlers[[1L]]) 10. │ │ │ └─base (local) doTryCatch(return(expr), name, parentenv, handler) 11. │ │ └─base::withCallingHandlers(...) 12. │ └─ggplot2 (local) f(l = layers[[i]], d = data[[i]]) 13. │ └─l$compute_statistic(d, layout) 14. │ └─ggplot2 (local) compute_statistic(..., self = self) 15. │ └─self$stat$compute_layer(data, self$computed_stat_params, layout) 16. │ └─ggplot2 (local) compute_layer(..., self = self) 17. │ └─rlang::check_installed("MASS", reason = "for calculating 2D density.") 18. │ └─base::stop(cnd)
解决方案
完善依赖声明与命名空间导入
- 在DESCRIPTION的Imports中明确MASS的最低兼容版本(例如
MASS (>= 7.3-58.1)),避免版本兼容问题。 - 在NAMESPACE文件中添加
importFrom(MASS, kde2d),确保包加载时MASS的核心函数被导入到包的命名空间,让ggplot2能正常调用该函数。
- 在DESCRIPTION的Imports中明确MASS的最低兼容版本(例如
显式检查依赖可用性
- 在调用
stat_density_2d的函数开头,添加依赖检查代码:if (!requireNamespace("MASS", quietly = TRUE)) { stop("MASS包是必需的,请先安装:install.packages('MASS')", call. = FALSE) }
这能确保在运行关键代码前,MASS已正确安装。
- 在调用
验证rhub环境的依赖安装
- 查看rhub检查的完整日志,确认MASS是否成功安装。若存在安装失败(如网络或镜像问题),可在rhub调用时指定稳定的CRAN镜像,或手动触发依赖重新安装。
替代方案:切换2D密度计算实现
- 若MASS依赖问题持续,可考虑改用无需MASS的2D密度统计方法,例如
ggdensity包的stat_density_2d_fast,或手动计算密度后再绘图。
- 若MASS依赖问题持续,可考虑改用无需MASS的2D密度统计方法,例如
内容的提问来源于stack exchange,提问作者Sebastian H
相关产品推荐
相关产品推荐

