Created
February 27, 2025 08:58
-
-
Save RaphaelS1/d56c9ddc7c3d3ea87ad47e8b2c5725f4 to your computer and use it in GitHub Desktop.
Get MLE estimate from a distr6 distribution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(distr6); library(stats4);library(data.table) | |
mleEstimate <- function(distr, data, method = "BFGS", fixed = list(), nobs, ...){ | |
p = as.data.table(distr$parameters()) | |
p = subset(p, subset = p$settable, select = c("id","value")) | |
f = vector("list",length(p$id)) | |
names(f) = p$id | |
LL <- function(){} | |
formals(LL) = f | |
body(LL) = substitute({ | |
-sum(do.call(distribution$new, pars)$pdf(data), log = TRUE) | |
}, list( | |
pars = eval(parse(text = paste0("alist(",paste0(p$id, "=", p$id, collapse = ","),")"))), | |
distribution = get(distr$name) | |
)) | |
s = as.list(p$value) | |
names(s) = p$id | |
mle = stats4::mle(minuslogl = LL, | |
start = s, | |
method = method, | |
fixed = fixed, | |
nobs = nobs, | |
...)@coef | |
do.call(get(distr$name)$new, as.list(round(mle, 5))) | |
} | |
mleEstimate(distr = Normal$new(mean = 2, sd = 2), data = rnorm(1000)) | |
mleEstimate(distr = Exponential$new(rate = 2), data = rexp(1000, rate = 2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment