library(ggplot2)
library(ggExtra)
library(gridExtra)
# Example 1: Sampling from the Truncated Normal distribution
set.seed(1234)
mu = c(0, 1)
Sigma = matrix(c(1,0.70,0.70,3), 2, 2)
lower = c(-2, -3)
upper = c(3, 3)
sample1 = rtelliptical(5e4, mu, Sigma, lower, upper, dist="Normal")
# Histogram and density for variable 1
ggplot(data.frame(sample1), aes(x=X1)) +
geom_histogram(aes(y=after_stat(density)), colour="black", fill="grey", bins=15) +
geom_density(color="red") + labs(x=bquote(X[1]), y="Density") + theme_bw()
# Histogram and density for variable 2
ggplot(data.frame(sample1), aes(x=X2)) +
geom_histogram(aes(y=after_stat(density)), colour="black", fill="grey", bins=15) +
geom_density(color="red") + labs(x=bquote(X[2]), y="Density") + theme_bw()
# \donttest{
# Example 2: Sampling from the Truncated Logistic distribution
# Function for plotting the sample autocorrelation using ggplot2
acf.plot = function(samples){
p = ncol(samples); n = nrow(samples); q1 = qnorm(0.975)/sqrt(n); acf1 = list(p)
for (i in 1:p){
bacfdf = with(acf(samples[,i], plot=FALSE), data.frame(lag, acf))
acf1[[i]] = ggplot(data=bacfdf, aes(x=lag,y=acf)) + geom_hline(aes(yintercept=0)) +
geom_segment(aes(xend=lag, yend=0)) + labs(x="Lag", y="ACF", subtitle=bquote(X[.(i)])) +
geom_hline(yintercept=c(q1,-q1), color="red", linetype="twodash") + theme_bw()
}
return (acf1)
}
set.seed(5678)
mu = c(0, 0)
Sigma = matrix(c(1,0.70,0.70,1), 2, 2)
lower = c(-2, -2)
upper = c(3, 2)
# Sample autocorrelation with no thinning
sample2 = rtelliptical(10000, mu, Sigma, lower, upper, expr="exp(1)^(-t)/(1+exp(1)^(-t))^2")
grid.arrange(grobs=acf.plot(sample2), top="Logistic distribution with no thinning", nrow=1)
# Sample autocorrelation with thinning = 3
sample3 = rtelliptical(10000, mu, Sigma, lower, upper, expr="exp(1)^(-t)/(1+exp(1)^(-t))^2",
thinning=3)
grid.arrange(grobs=acf.plot(sample3), top="Logistic distribution with thinning = 3", nrow=1)
# }
# Example 3: Sampling from the Truncated Kotz-type distribution
set.seed(5678)
mu = c(0, 0)
Sigma = matrix(c(1,-0.5,-0.5,1), 2, 2)
lower = c(-2, -2)
upper = c(3, 2)
sample4 = rtelliptical(2000, mu, Sigma, lower, upper, gFun=function(t){t^(-1/2)*exp(-2*t^(1/4))})
f1 = ggplot(data.frame(sample4), aes(x=X1,y=X2)) + geom_point(size=0.50) +
labs(x=expression(X[1]), y=expression(X[2]), subtitle="Kotz(2,1/4,1/2)") + theme_bw()
ggMarginal(f1, type="histogram", fill="grey")
Run the code above in your browser using DataLab