From 9a748f39699a38f480b10a44cf7510efc2e771da Mon Sep 17 00:00:00 2001 From: Hugo Gruson Date: Mon, 6 Nov 2023 17:35:36 +0100 Subject: [PATCH] Sum loglikelihoods before exponentiating --- R/likelihood.R | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/R/likelihood.R b/R/likelihood.R index 63b33af1..68f0f24c 100644 --- a/R/likelihood.R +++ b/R/likelihood.R @@ -134,17 +134,19 @@ likelihood <- function(chains, statistic = c("size", "length"), offspring_dist, likelihoods[sx[!(sx %in% exclude)]] }) - ## transform log-likelihoods into likelihoods if required - if (isFALSE(log)) { - chains_likelihood <- lapply(chains_likelihood, exp) + ## if individual == FALSE, return the joint log-likelihood + ## (sum of the log-likelihoods) + if (!individual) { + chains_likelihood <- vapply(chains_likelihood, sum, 0) } - ## if individual == FALSE, return the joint log-likelihood - ## (sum of the log-likelihoods), if log == TRUE, else - ## multiply the likelihoods - if (isFALSE(individual)) { - summarise_func <- ifelse(log, sum, prod) - chains_likelihood <- vapply(chains_likelihood, summarise_func, 0) + ## transform log-likelihoods into likelihoods if required + if (!log) { + if (individual) { + chains_likelihood <- lapply(chains_likelihood, exp) + } else { + chains_likelihood <- exp(chains_likelihood) + } } return(chains_likelihood)