# Statistical software like R can be used to draw random numbers from some
# specified distribution. These numbers are not truly random, but appear
# indistinguishable from actual random numbers. To make the analysis
# replicable, one must fix the so-called 'seed', which ensures that every time
# the code is run, the same quasi-random numbers are drawn.
# Fix seed:
set.seed(50) # choose some (any) number here
# Uniform distribution:
runif(3) # generate 3 (independent) draws from U(0,1)
runif(3, 0, 1) #same
runif(3, -3, 8) # generaate 3 (independent) draws from U(-3,8)
dunif(1.3, -3, 8) # evaluate pdf of U(-3,8) at x=1.3
punif(1.3, -3, 8) # evaluate cdf of U(-3,8) at x=1.3
qunif(0.2, -3, 8) # compute 20th percentile (point corresponding to cdf of 0.2)
# see ?runif for documentation for all these commands pertaining to Uniform
# disttribution
# note that these functions can also be applied to vectors
# Normal distribution:
rnorm(3) # generate 3 (independent) draws from standard Normal
rnorm(3, 2, 1) # generate 3 (independent) draws from Normal with mean 2 and standard deviation 1
dnorm(1.3, 2, 1) # return pdf at x=1.3
pnorm(1.3, 2, 1) # return cdf at x=1.3
qnorm(0.2, 2, 1) # compute 20th percentile
# hence, to get critical values for two-sided 95% level test:
qnorm(0.025) # 2.5th percentile of N(0,1)
qnorm(0.975) # 97.5th percentile of N(0,1)
# see ?rnorm for documentation for all these commands pertaining to Normal
# disttribution
# t-distribution:
rt(3, 32) # 3 draws, df=32
# dt, pt, qt exist too; see ?rt
# Chi-squared:
dchisq(3, 9) # 3 draws, df=9
# dchisq, pchisq, qchisq exist too; see ?rchisq
# Inverse Gamma:
library(invgamma)
rinvgamma(3, 10, 2) # 5 draws from IG with shape 10 and rate 2
# can also specify shape and scale; see
`?`(rinvgamma)
# dinvgamma, pinvgamma, qinvgamma exist too; see ?rinvgamma
# Multivariate Normal:
library(mvtnorm)
= c(0, 2)
vMeans = matrix(data = c(0.4, 0.2, 0.2, 0.9), nrow = 2, ncol = 2)
mVariance rmvnorm(3, vMeans, mVariance) # 3 draws from multivariate Normal with specified mean and variance
# dmvnorm exists too; see ?rmvnorm
# Inverse Wishart:
library(MCMCpack)
= 5
nu = matrix(data = c(0.4, 0.2, 0.2, 0.9), nrow = 2, ncol = 2)
mS riwish(v = nu, S = mS) #single draw
# diwish exists too; see ?riwish
# The multinomial distribution is a manually defined, discrete-valued
# univariate distribution.
# Define a discrete distribution with the following possible realizations
# (outcomes):
= c(3.4, 5.3, 3.2)
vOutcomes
# Sample 3 times from these elements/outcomes (with replacement):
sample(vOutcomes, 3, replace = TRUE)
# by default, R assumes that all elements have equal probabilities
# alternatively supply vector of probabilities:
= c(0.2, 0.2, 0.6)
vProbabilities sample(vOutcomes, 3, replace = TRUE, prob = vProbabilities)
# Fit Kernel-density-estimate on vector 'vOutcomes':
density(vOutcomes) # assuming equal probabilities
density(vOutcomes, weights = vProbabilities) # supplying vector of probabilities