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)