R语言为截断数据拟合gamma分布时dtruncated_gamma未定义错误如何解决
截断Gamma分布拟合函数报错解决方案
错误原因
fitdistrplus::fitdist 接收字符串格式的分布名时,会自动在全局环境搜索匹配 d<分布名>、p<分布名> 格式的分布函数。你在fit_gamma内部定义的dtruncated_gamma、ptruncated_gamma是函数内部的局部对象,fitdist执行时无法访问,因此抛出找不到函数的错误。
修复方案
不需要将自定义函数注册到全局环境,直接把密度、累计分布函数以列表形式传入fitdist的distr参数即可,修改后的函数代码如下:
# 为截断数据拟合gamma分布 fit_gamma <- function(y, left = NULL, right = NULL){ dtruncated_gamma <- function(x, scale, shape) { dtrunc(x, "gamma", a = left, b = right, scale = scale, shape = shape) } ptruncated_gamma <- function(q, scale, shape) { ptrunc(q, "gamma", a = left, b = right, scale = scale, shape = shape) } fitdistrplus::fitdist(y, distr = list(dens = dtruncated_gamma, pdist = ptruncated_gamma), method = "mle", lower = c(scale = 0, shape = 0), start = list(scale = 149919.5, shape = 0.8955081)) }
功能验证
调用fit_gamma(f, left = 30000, right = Inf)即可正常返回拟合结果。
可选优化
如果需要适配不同的输入数据,避免写死初始值,可以先通过矩估计计算普通Gamma分布的参数作为初始值,替换原有start参数即可:
# 自动估算初始值 start_vals <- fitdistrplus::fitdist(y, "gamma", method = "mme")$estimate
内容的提问来源于stack exchange,提问作者mharinga
相关产品推荐
相关产品推荐

