Ref:
We’ll show egs from the package distr
that is capable of creating combinations of known distributions.
library(distr)
Let’s start by creating simple distributions and plots:
N1 <- Norm()
plot(N1)
B1 <- Binom(prob=0.25, size=2)
plot(B1)
## NULL
Bt1 <- Beta(3,9)
plot(Bt1, to.draw.arg="d") # draw just the pdf
U1 <- Unif(Min=-1,Max=1)
plot(U1, to.draw.arg="p") # draw just the cdf
E1 <- Exp(rate=2)+2
plot(E1, to.draw.arg=c("d","q")) # draw the pdf and the quantile
# produce a discrete distribution with support (1,5,7,21) with corresponding probabilities (.1,.1,.6,.2)
DD <- DiscreteDistribution(supp = c(1,5,7,21), prob = c(0.1,0.1,0.6,0.2))
plot(DD, panel.first=grid(), lty=1:4, lwd=c(1,2,4), col.vert="gold", col.hor = "blue",
col.points=c("red","black"), cex.points=1, pch.u=5, pch.a=19, vertical=T)
## $lty
## 1:4
##
## $lwd
## c(1, 2, 4)
plot(DD, do.points=FALSE, vertical=FALSE)
## NULL
plot(Nbinom(size=4, prob=0.3), cex.points=1.2, pch.u=20, pch.a=10)
## NULL
plot(Chisq(), log="xy", ngrid=100)
These objects can be acessed with the typical R’s d
, p
, q
and r
:
d(N1)(0) # density, pdf_AC(0)
## [1] 0.3989423
d(N1)(1)
## [1] 0.2419707
p(N1)(0.6745) # p(AC <= 0.6745)
## [1] 0.7500033
distr::q(N1)(0.75) # 75% quantile
## [1] 0.6744898
r(N1)(20) # generate 20 random numbers from the distribution
## [1] -0.153241771 1.529221179 -0.001043751 0.242755462 -1.461567423
## [6] 1.433645342 0.429453555 -1.023760221 -1.813338230 0.067470653
## [11] 0.367217323 0.635847502 2.135205878 -0.875030150 0.150371841
## [16] 0.917199284 0.268455735 0.299268740 -0.810842487 0.814442814
par(mfcol=c(1,1))
hist(r(N1)(5e3), breaks=50, prob=T)
It’s also possible to define distribution with a given pdf function:
D1 <- AbscontDistribution(d = function (x) exp(-abs(x/2)^3 ), withStand = TRUE)
plot(D1)
D2 <- AbscontDistribution(q = function (x) x^2, withStand = TRUE)
plot(D2)
There are available quite general arithmetical operations to distribution objects, generating new image distributions automatically. Arithmetics on distribution objects are understood as operations on corresponding random variables (r.v.’s) and not on distribution functions or densities. E.g.
\[\mathcal{N}(0,1) + 3 * \mathcal{N}(0,1) + 2\]
returns a distribution object representing the distribution of the r.v. \(X+3*Y+2\) where \(X\) and \(Y\) are r.v.’s i.i.d. \(\mathcal{N}(0,1)\).
N2 <- Norm() + 3*Norm() + 2
plot(N2)