###############
## Example 1 ##
mymeanlog <- exp(0.5) # meanlog
mysdlog <- exp(-1.5) # sdlog
LL <- 3.5 # Lower bound
UL <- 8.0 # Upper bound
## Quantiles:
pp <- 1:10 / 10
(quants <- qtrunclnorm(p = pp , min.support = LL, max.support = UL,
mymeanlog, mysdlog))
sum(pp - ptrunclnorm(quants, min.support = LL, max.support = UL,
mymeanlog, mysdlog)) # Should be zero
###############
## Example 2 ##
set.seed(230723)
nn <- 3000
## Truncated log-normal data
trunc_data <- rtrunclnorm(nn, mymeanlog, mysdlog, LL, UL)
## non-truncated data - reference
nontrunc_data <- rtrunclnorm(nn, mymeanlog, mysdlog, 0, Inf)
if (FALSE) {
## Densities
plot.new()
par(mfrow = c(1, 2))
plot(density(nontrunc_data), main = "Non-truncated Log--normal",
col = "green", xlim = c(0, 15), ylim = c(0, 0.40))
abline(v = c(LL, UL), col = "black", lwd = 2, lty = 2)
plot(density(trunc_data), main = "Truncated Log--normal",
col = "red", xlim = c(0, 15), ylim = c(0, 0.40))
## Histograms
plot.new()
par(mfrow = c(1, 2))
hist(nontrunc_data, main = "Non-truncated Log--normal", col = "green",
xlim = c(0, 15), ylim = c(0, 0.40), freq = FALSE, breaks = 22,
xlab = "mu = exp(0.5), sd = exp(-1.5), LL = 3.5, UL = 8")
abline(v = c(LL, UL), col = "black", lwd = 4, lty = 2)
hist(trunc_data, main = "Truncated Log--normal", col = "red",
xlim = c(0, 15), ylim = c(0, 0.40), freq = FALSE,
xlab = "mu = exp(0.5), sd = exp(-1.5), LL = 3.5, UL = 8")
}
## Area under the estimated densities
# (a) truncated data
integrate(approxfun(density(trunc_data)),
lower = min(trunc_data) - 0.1,
upper = max(trunc_data) + 0.1)
# (b) non-truncated data
integrate(approxfun(density(nontrunc_data)),
lower = min(nontrunc_data),
upper = max(nontrunc_data))
Run the code above in your browser using DataLab