Home » excel » r – How to write a nested IF and RAND excel statement

r – How to write a nested IF and RAND excel statement

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m trying to generate a column with rows of random binary 1’s and 0’s in R.

In excel, I can write this in a new column as if(rand()< $A$1,1,0).

Where $A$1 = 0.1. So if any random numbers are less than 0.1, it will return 1. As such, the results would print a column with random rows of 1 and 0.

In R, I wrote down

data$binary <- ifelse(runif(1,0,1)<0.1,1,0) 

and all I’m getting is only values of 1.

If the random number generated is less than 0.1, then return 1 else 0.

Much help is appreciated!

How to&Answers:

With runif you can use

n <- 10
+(runif(n,0,1) < 0.1)

Since +(runif(n,0,1) < 0.1) on an average would be 1 for 10% of n, you can also use sample with probability argument which would give you the same result.

sample(c(0, 1), n, replace = TRUE, prob = c(0.9, 0.1))

Answer:

Note that ifelse() is a vectorizing operator, so the output keeps the same dimensions of the condition. In your code, runif(1,0,1) is a single value, thus giving single-valued output when using ifelse().

Maybe you should try it like below

df$binary <- ifelse(df$A<0.1,1,0)

such that

> df
           A binary
1  0.2875775      0
2  0.7883051      0
3  0.4089769      0
4  0.8830174      0
5  0.9404673      0
6  0.0455565      1
7  0.5281055      0
8  0.8924190      0
9  0.5514350      0
10 0.4566147      0

DATA

set.seed(123)
df <- data.frame(A = runif(10,0,1))