# for a vector:
tst <- rgamma(1e5, 2.5, 2)
hdi(tst)
hdi(tst, credMass=0.8)
# For comparison, the symmetrical 80% CrI:
quantile(tst, c(0.1,0.9))
# for a density:
dens <- density(tst)
hdi(dens, credMass=0.8)
# Now a data frame:
tst <- data.frame(mu = rnorm(1e4, 4, 1), sigma = rlnorm(1e4))
hdi(tst, 0.8)
apply(tst, 2, quantile, c(0.1,0.9))
tst$txt <- LETTERS[1:25]
hdi(tst, 0.8)
# For a function:
hdi(qgamma, 0.8, shape=2.5, rate=2)
# and the symmetrical 80% CrI:
qgamma(c(0.1, 0.9), 2.5, 2)
# A multimodal distribution:
set.seed(2020)
tst2 <- c(rnorm(500, 30, 3), rnorm(200, 50, 1.5), 60 + rexp(200, 0.1))
hist(tst2, breaks = 100, freq=FALSE)
(hdiMC <- hdi(tst2))
segments(hdiMC[1], 0, hdiMC[2], 0, lwd=4, col='red', lend='butt')
# This is a valid 95% CrI, but not a Highest Density Interval
dens2 <- density(tst2, bw="SJ") # not the default for 'bw', see ?density
lines(dens2, lwd=2, col='blue')
(hdiD <- hdi(dens2, allowSplit=TRUE))
(ht <- attr(hdiD, "height"))
segments(hdiD[, 1], ht, hdiD[, 2], ht, lwd=4, col='blue', lend='butt')
# This is the correct 95% HDI.
Run the code above in your browser using DataLab