Skip to content

Instantly share code, notes, and snippets.

@ilapros
Last active May 31, 2024 07:18
Show Gist options
  • Save ilapros/b35707ede59f803917134c0e41b29577 to your computer and use it in GitHub Desktop.
Save ilapros/b35707ede59f803917134c0e41b29577 to your computer and use it in GitHub Desktop.
getting parameters for the lognormal and gamma to match given values for first and second moment
### I use these to generate data for teaching examples
lnparFromMoments <- function(expectation, variance){
m <- expectation; s2 <- variance ; m2 <- m^2
mu <- log(m2/sqrt(s2+m2))
sigma2 <- log(1+s2/m2)
c(mu, sqrt(sigma2))
}
gammaparFromMoments <- function(expectation, variance, scale = FALSE){
m <- expectation; s2 <- variance ; m2 <- m^2
shape_alpha <- m2/s2
rate_beta <- m/s2
if(scale) {shape_kappa <- shape_alpha; scale_theta <- 1/rate_beta}
if(!scale) return(c(shape_alpha, rate_beta))
if(scale) return(c(shape_kappa, scale_theta))
}
meansd <- function(x) c(mean(x), sd(x))
meanvar <- function(x) c(mean(x), var(x))
# (a<- lnparFromMoments(4,1.5))
# meanvar(exp(rnorm(10000, a[1],a[2])))
# (a<- gammaparFromMoments(160,5, scale = TRUE))
# meanvar(rgamma(10000, shape = a[1], scale = a[2]))
scale01 <- function(x) (x-min(x))/diff(range(x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment