[R] Generating uniformly distributed correlated data.

Sarah Goslee sarah.goslee at gmail.com
Sun Feb 20 14:45:26 CET 2011


On Sun, Feb 20, 2011 at 12:18 AM, Peter Langfelder
<peter.langfelder at gmail.com> wrote:
> On Sat, Feb 19, 2011 at 6:17 PM, Søren Faurby
> <soren.faurby at biology.au.dk> wrote:
>> I wish to generate a vector of uniformly distributed data with a defined
>> correlation to another vector
>>
>> The only function I have been able to find doing something similar is corgen
>> from the library ecodist.
>>
>> The following code generates data with the desired correlation to the vector
>> x but the resulting vector y is normal and not uniform distributed
>>
>> library(ecodist)
>> x <- runif(10^5)
>> y <- corgen(x=x, r=.5)$y
>>
>> Do anyone know a similar function generating uniform distributed data or a
>> way of transforming y to the desired distribution while keeping the
>> correlation between x and y
>
> Hi Soren,
>
> I'm not aware of such functions, but you can try the following code:
>
> # generate some x
> n = 100
> x = runif(n)
> r = 0.5;
>
> y = r * scale(x) + sqrt(1-r^2) * scale(runif(n));
>
> cor(x,y)
>

That's the method used in corgen() and it produces a normally-distributed y even
if x is uniform.

Correlated normals are a much easier problem than correlated uniforms.

Maybe some of the other links will give you ideas.

Sarah
--
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list