This page contains related R codes for STAT 51100 Section 010. This page is for Chapter 4, some continuous random variables. We will cover several distributions: Normal distribution, Exponential distribution, Gamma distribution, Weibull distribution, and log-normal distribution.

We can use R to simulate random variables from the above distribution, and we can also use R to calculate the probability mass function, cumulative distribution function, and also draw the probability histogram.

General function format are

 d*(x, parameters) p*(x, parameters) q*(p, parameters) r*(sample size, parameters)

Here

1. d* function will calculate the value of the probability mass function at value x. Parameters are needed to be specified.

2. p* function will calculate the value of the cumulative distribution function at value x, i.e., $$P(X \leq x)$$.

3. q* function will calculate the percentile at value $$p$$, see this function after we learn percentile in Chapter 4.

4. r* function will simulate a ramdom sample of size as the sample size specified in this function, with a specified distribution.

A useful function help.search() to check how to use the above functions. We will not simulate discrete random variables in this tutorial.

### 1. Normal distribution

The Normal distribution has the form as dnorm, pnorm, qnorm, rnorm. The following calculates the pdf for a standard normal distribution between -5 and 5.

x<-seq(-5, 5, by=0.01)
y<-dnorm(x)
plot(x, y, type='l', xlab='X', ylab='Density', main='Standard Normal Distribution')
abline(h=0, lty=2)
abline(v=0, lty=2)

We can also specify different mean and variance/standard deviation.

y<-dnorm(x, mean=1, sd=2)
plot(x, y, type='l', xlab='X', ylab='Density', main='Normal Distribution: N(1, 2)')
abline(h=0, lty=2)
abline(v=1, lty=2)

We will illustrate how to calculate $$P(X\leq 1.25)$$, $$P(-0.38 \leq X \leq 1.25)$$ using the (difference of the) CDF(s).

pnorm(1.25)
## [1] 0.8943502
pnorm(1.25)-pnorm(-.38)
## [1] 0.5423775

Now we will illustrate how to find percentile of a standard normal distribution, the following will find .90, .95, .975 and .99 percentiles of standard normal distribution

q<-c(.9, .95, .975, .99)
qnorm(q)
## [1] 1.281552 1.644854 1.959964 2.326348

We can also simulate some data from standard normal distribution and draw histogram of it

x<-rnorm(1000)
hist(x, freq=FALSE)
t<-seq(-5, 5, by=0.1)
y<-dnorm(t)
lines(t, y, col=2)