Learn R Programming

ecolottery (version 1.0.1)

tcor: Generates Correlated Traits

Description

Create two random vectors of traits correlated between each other or a vector of traits correlated to an existing one. The linear correlation is defined by the parameter rho.

Usage

tcor(n, rho = 0.5, mar.fun = rnorm, x = NULL, ...)

Value

Return a data.frame with two numeric columns, each column defining a trait.

Arguments

n

the integer number of values to be generated.

rho

a numeric parameter defining the linear correlation between the two traits (default is 0.5). It must belong to the interval [-1, 1].

x

an vector of numeric values. Default is NULL.

mar.fun

a function defining the random generation for the trait distribution. Default is rnorm.

...

other arguments for the mar.fun() function.

Author

P. Denelle F. Munoz

Details

rho parameter is set to 0.5 by default. x = NULL by default. Code adapted from: http://stats.stackexchange.com/questions/15011/generate-a-random-variable-with-a-defined-correlation-to-an-existing-variable

Examples

Run this code
# With no predefined trait
traits <- tcor(n = 10000, rho = 0.8)
plot(traits[, 1], traits[, 2])
cor(traits[, 1], traits[, 2])

# With existing trait
existing_trait <- rnorm(10000, 10, 1)
traits <- tcor(n = 10000, rho = 0.8, x = existing_trait)
plot(traits[, 1], traits[, 2])
cor(traits[, 1], traits[, 2])

Run the code above in your browser using DataLab