mardi 30 avril 2019

what's wrong with runif (or maybe me) in R?

I am trying to generate a random variable fron uniform distribution that also depends on random variable.

Ideally, I want z2 to be a random variable as well.

For example,

set.seed(123)
#generate first random variable z1
z1 <- runif(10,0,1)
#generate secondrandom variable z2
z2 <- ifelse(z1>= 0.7, runif(1,0.6,0.9), runif(1,0.2,0.5))
df <- data.frame(z1,z2)

But if you look at z2 it contains only two levels.

          z1        z2
1  0.2875775 0.3360002
2  0.7883051 0.8870500
3  0.4089769 0.3360002
4  0.8830174 0.8870500
5  0.9404673 0.8870500
6  0.0455565 0.3360002
7  0.5281055 0.3360002
8  0.8924190 0.8870500
9  0.5514350 0.3360002
10 0.4566147 0.3360002

We can generate 1000 number and summarize the results.

set.seed(123)
#generate first random variable z1
z1 <- runif(1000,0,1)
#generate secondrandom variable z2
z2 <- ifelse(z1>= 0.7, runif(1,0.6,0.9), runif(1,0.2,0.5))

table(df$z2)

0.352099318057299 0.655542095610872 
              707               293








Aucun commentaire:

Enregistrer un commentaire