###############
## Example 1 ##
mymu <- 2.1 # mu
mysd <- 1.0 # sigma
LL <- -1.0 # Lower bound
UL <- 3.0 # Upper bound
## Quantiles:
pp <- 1:10 / 10
(quants <- qtruncnorm(p = pp , min.support = LL, max.support = UL,
mean = mymu, sd = mysd))
sum(pp - ptruncnorm(quants, min.support = LL, max.support = UL,
mean = mymu, sd = mysd)) # Should be zero
###############
## Example 2 ##
## Parameters
set.seed(230723)
nn <- 3000
mymu <- 12.7 # mu
mysigma <- 3.5 # sigma
LL <- 6 # Lower bound
UL <- 17 # Upper bound
## Truncated-normal data
trunc_data <- rtruncnorm(nn, mymu, mysigma, LL, UL)
## non-truncated data - reference
nontrunc_data <- rnorm(nn, mymu, mysigma)
if (FALSE) {
## Densities
par(mfrow = c(1, 2))
plot(density(nontrunc_data), main = "Non-truncated ND",
col = "green", xlim = c(0, 25), ylim = c(0, 0.15))
abline(v = c(LL, UL), col = "black", lwd = 2, lty = 2)
plot(density(trunc_data), main = "Truncated ND",
col = "red", xlim = c(0, 25), ylim = c(0, 0.15))
## Histograms
plot.new()
par(mfrow = c(1, 2))
hist(nontrunc_data, main = "Non-truncated ND", col = "green",
xlim = c(0, 25), ylim = c(0, 0.15), freq = FALSE, breaks = 22,
xlab = "mu = 12.7, sd = 3.5, LL = 6, UL = 17")
abline(v = c(LL, UL), col = "black", lwd = 4, lty = 2)
hist(trunc_data, main = "Truncated ND", col = "red",
xlim = c(0, 25), ylim = c(0, 0.15), freq = FALSE,
xlab = "mu = 12.7, sd = 3.5, LL = 6, UL = 17")
}
## Area under the estimated densities
# (a) truncated data
integrate(approxfun(density(trunc_data)),
lower = min(trunc_data) - 1,
upper = max(trunc_data) + 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