Create a Random Vector With Fixed Correlation With Another Vector
Source:R/rescale.R
rand_with_cor.Rdrand_with_cor() creates a vector of random number that has
correlation rho with a given vector y.
Also mean and standard deviation of the random vector
can be fixed by the user. By default, they will be equal to the mean
and standard deviation of y, respectively.
Source
This solution is based on an answer by whuber on Cross Validated.
Examples
x <- runif(1000, 5, 8)
# create a random vector with positive correlation
y1 <- rand_with_cor(x, 0.8)
all.equal(cor(x, y1), 0.8)
#> [1] TRUE
# create a random vector with negative correlation
# and fixed mean and standard deviation
y2 <- rand_with_cor(x, -0.3, 2, 3)
all.equal(cor(x, y2), -0.3)
#> [1] TRUE
all.equal(mean(y2), 2)
#> [1] TRUE
all.equal(sd(y2), 3)
#> [1] TRUE