[R] Simulate binary correlated data

Marbles max-ihmels at gmx.de
Tue Mar 5 22:22:06 CET 2013


Btw: I have done this for non-binary variables already. If anyone is
interested, it looks like this.
I am pretty new to R, so excuse the potentially unelegant code.

# Implement library 
library(ecodist)

# Prepare ACOutcome vector
ACOutcomes = c()

# Set desired variablelength & Number of simulations
VarLength = 1000
NSim = 10000

# Set desired range for correlations
rangeAB = c(0.0, 1.0)
rangeBC = c(0.0, 1.0)

# Start n simulation runs
n = 0
while(n < NSim) {n=n+1;

# Set desired correlations between Variables
DesCorAB = runif(1, rangeAB[1], rangeAB[2])
DesCorBC = runif(1, rangeBC[1], rangeBC[2]) 

# Simulate A and B with desired correlation between them
DatasetAB = corgen(len=VarLength, r=DesCorAB, epsilon=0.00)
A = DatasetAB$x
B = DatasetAB$y

# Option of saving correlation between A & B
cor(A, B, method = "pearson")

# Simulate C with desired correlation to B
C = corgen(x=B, r=DesCorBC, epsilon = 0.00)$y

# Calculate correlation between A & C
corAC = cor(A, C, method = "pearson")

# Save correlation AC into vector
ACOutcomes = append(ACOutcomes, corAC)

;}

# Show results: Mean, Minimum, Maximum
hist(ACOutcomes, breaks = 100)
mean(ACOutcomes)
min(ACOutcomes)
max(ACOutcomes)



--
View this message in context: http://r.789695.n4.nabble.com/Simulate-binary-correlated-data-tp4660366p4660382.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list