Correlated Random Numbers – R Code

This is simple R code for generating correlated random numbers using the package MASS and its built-in function mvrnorm. In the example below 3 correlated vectors of values are being generated with correlations of 0.5, 0.6 and 0.7, respectively.

## Generate Correlated Random Numbers

# clear environment and console
rm(list = ls())
cat("\014")

# install and load required packages
install.packages("MASS")
require(MASS)

# inputs
n = 1000 # number of random numbers
correl = matrix(c(1, 0.5, 0.6, 0.5, 1, 0.7, 0.6, 0.7, 1), ncol = 3)
mu = c(0, 0, 0) # Gaussian vectors of values

num = mvrnorm(n, mu, correl, empirical = TRUE)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s