cor.with | R Documentation |
Simulate a variable correlated at level 'r' with cector x (of the same length). Can either 'preserve' the mean and standard-deviation, leave standardizeed, or select new mean 'mn' and standard deviation 'st'.
cor.with(x, r = 0.5, preserve = FALSE, mn = NA, st = NA)
x |
existing variable, to which you want to simulate a new correlated variable |
r |
the 'expected' correlation you want to target (randomness will mean that the actual correlation will vary around this value) |
preserve |
logical, whether to preserve the same mean and standard deviation(SD) as x, for the new variable |
mn |
optional, set the mean for the new simulated variable [must also set st if using this] |
st |
optional, set the SD for the new simulated variable [must also set mn if using this] |
return the new variable with an expected correlation of 'r' with x
Nicholas Cooper
http://www.uvm.edu/~dhowell/StatPages/More_Stuff/CorrGen.html
sim.cor
X <- rnorm(10,100,14) cor.with(X,r=.5) # create a variable correlated .5 with X cor(X,cor.with(X)) # check the actual correlation # some variability in the actual correlation, so run 1000 times: print(mean(replicate(1000,{cor(X,cor.with(X))}))) cor.with(X,preserve=TRUE) # preserve original mean and standard deviation X[c(4,10)] <- NA # works fine with NAs, but new var will have same missing cor.with(X,mn=50,st=2) # specify new mean and standard deviation
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.