Skip to content

Instantly share code, notes, and snippets.

@hannesdatta
Created March 1, 2021 12:11
Show Gist options
  • Select an option

  • Save hannesdatta/7d4f41de1a0313df233790af4e564e7c to your computer and use it in GitHub Desktop.

Select an option

Save hannesdatta/7d4f41de1a0313df233790af4e564e7c to your computer and use it in GitHub Desktop.
Draw from four-dimensional normal distribution with specific correlation structure
#' Draw from variance-covariance matrix, given correlation rho (buggy!)
#'
#' The purpose of this function is to generate draws from
#' the variance-covariance matrix, given a specific correlation structure.
#' In particular, a four-dimensional correlation structure is drawn, in which
#' the first dimension (sales) is correlated with the remaining 3 dimensions
#' (marketing mix instruments) with *rho*, and the correlations among the 3 dimensions
#' (marketing mix instruments) is zero (or about zero).
#'
#' @param rho Correlation between the first dimension, and the remaining three dimensions
#'
#' @return N x 4 matrix, with each colun representing N draws from the variance-covariance
#' matrix.
#' @export
#'
#' @examples
#' errors <- draw_errors(.3) # works
#' errors <- draw_errors(.9) # does not work
draw_errors <- function(rho) {
# Specify correlation matrix
R = matrix(c(1, rho, rho, rho,
rho, 1, 0, 0,
rho, 0, 1, 0,
rho, 0, 0, 1), ncol = 4)
# Specify standard deviations
S <- c(sqrt(.2), sqrt(.5), sqrt(.5), sqrt(.5))
# Function to convert correlation matrix to covariance matrix
cor2cov <- function(R, S) {
sweep(sweep(R, 1, S, "*"), 2, S, "*")
}
# Generate covariance matrix
Sigma = cor2cov(R, S)
# Generate draws from var-covar
error = mvrnorm(n = N,
mu = c(0, 0, 0, 0),
Sigma = Sigma)
return(error)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment