[R] Random Normal Variable Correlated to an Existing BinomialVariable

Enrico Schumann enricoschumann at yahoo.de
Wed Apr 27 09:06:41 CEST 2011



Hi,

do you know the parameters of the binomial variate? then maybe you could use
something like the code below. as Petr pointed out, it is generally not
guaranteed that you can create variates with any linear correlation (ie,
depending on the parameters of the binomial)

n <- 100    # how many variates

# your binomial variate (example)
size <- 10; prob <- 0.2
vecB <- rbinom(n, size = size, prob = prob)

rho <- 0.75  # desired cor
m   <- 0.5   # mean and sd of Gaussian
sig <- 2 

rho <- 2*sin(rho*pi/6)  # a small correction
C <- matrix(rho, nrow = 2, ncol = 2)
diag(C) <- 1; C <- chol(C)

# (1) transform binomial to Gaussian
X1 <- qnorm(pbinom(vecB, size = size, prob = prob))
# (2) create another Gaussian
X2 <- rnorm(n)
X <- cbind(X1,X2)
# (3) induce correlation (does not change X1)
X <- X %*% C
# (4) make uniforms
U <- pnorm(X)
# (5) ... and put them into the inverses
vecB1 <- qbinom(U[,1],size,prob)
vecG <- qnorm(U[,2], mean = m, sd = sig)

# check
plot(vecB1,vecG)
cor(vecB1,vecG)
all.equal(vecB1,vecB)
sd(vecG)

(linear correlation is not affected by linear transformation, so you can
enforce exactly your desired mean and standard deviation for the Gaussian by
rescaling it in the end)


regards,
enrico

> -----Ursprüngliche Nachricht-----
> Von: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] Im Auftrag von Shane Phillips
> Gesendet: Montag, 25. April 2011 01:00
> An: R-help at r-project.org
> Betreff: [R] Random Normal Variable Correlated to an Existing 
> BinomialVariable
> 
> Hi, R-Helpers!
> 
> I have a dataframe that contains a binomial variable.  I need 
> to add another random variable drawn from a normal 
> distribution with a specific mean and standard deviation.  
> This variable also needs to be correlated with the existing 
> binomial variable with a specific correlation (say .75).  Any ideas?
> 
> Thanks!
> 
> Shane
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list