1

I would like to create a function that fits a gamma distribution to truncated data.

Let's say I have the following truncated data:

# Simulate some truncated data from gamma distribution
library(truncdist)
library(fitdistrplus)

set.seed(1)
e <- rgamma(1000, scale = 148099.5, shape = 0.4887023)
left_tr <- 30000
f <- e[e > left_tr] # truncated data

Then following Fitting a lognormal distribution to truncated data in R, I would fit a gamma distribution to the truncated data.

# Fitting a gamma distribution to truncated data
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, "truncated_gamma", 
                        method = "mle",
                        lower = c(0,0), 
                        start = list(scale = 149919.5, shape = 0.8955081))
}

fit_gamma() returns an error:

fit_gamma(f, left = 30000, right = Inf)
#> Error in fitdistrplus::fitdist(y, "truncated_gamma", method = "mle", lower = c(0, : The  dtruncated_gamma  function must be defined

What is the way to solve this error?

Created on 2021-10-25 by the reprex package (v2.0.1)

mharinga
  • 1,708
  • 10
  • 23
  • 1
    It looks like `fitdist` isn't looking for `dtruncated_gamma` and `ptruncated_gamma` in the right environment in order to create `truncated_gamma`. Try taking everything out of your `fit_gamma` function or use `<<-`. See https://stackoverflow.com/questions/24934716/where-to-define-distribution-function-to-be-used-with-fitdist-fitdistrplus-or – jblood94 Oct 25 '21 at 21:20

0 Answers0