Skip to content

Instantly share code, notes, and snippets.

@geofferyzh
Created April 17, 2012 14:34
Show Gist options
  • Save geofferyzh/2406368 to your computer and use it in GitHub Desktop.
Save geofferyzh/2406368 to your computer and use it in GitHub Desktop.
RinAction - R Functions - Probability Functions
#################################################
## Probability Functions ##
#################################################
########################
# Normal Distribution
# - density (dnorm)
# - distribution (pnorm)
# - quantile (qnorm)
# - random deviate generation (rnorm)
########################
# standard normal curve on the interval [–3,3]
x <- pretty(c(-3,3), 30)
y <- dnorm(x)
plot(x, y,
type = "l",
xlab = "Normal Deviate",
ylab = "Density",
yaxs = "i"
)
a <- pnorm(1.96)
a
# 90th percentile of a normal distribution with
# a mean of 500 and a standard deviation of 100
p90 <- qnorm(.9, mean=500, sd=100)
# Generate 50 random normal deviates with a mean of
# 50 and a standard deviation of 10
ran50 <- rnorm(50, mean=50, sd=10)
################################
# Random NUmber Generation
################################
# Set the seed
runif(5)
runif(5) # should get different numbers
set.seed(1234)
runif(5)
set.seed(1234)
runif(5) # should get same numbers after setting the seed
#################################
# Multivariate Normal Data
#################################
#In simulation research and Monte Carlo studies, you often want to draw data from
#multivariate normal distribution with a given mean vector and covariance matrix.
library(MASS)
options(digits=3)
set.seed(1234)
mean <-c(230.7, 146.7, 3.6)
sigma <- matrix(c(15360.8, 6721.1,-47.1,
6721.1, 4700.9, -16.5,
-47.1, -16.5, 0.3), nrow=3, ncol=3)
mydata <- mvrnorm(500, mean, sigma)
mydata <- as.data.frame(mydata)
names(mydata) <- c("y","x1","x2")
dim(mydata)
head(mydata, n=10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment