Search code examples
rrandomsamplingresampling

Matching output of sample() with rbinom() in R?


Maybe this is too simple of a question but shouldn't A and B be exactly equal in my below R code:

set.seed(0)
A <- sample(0:1, 50, prob = rep(.5, 2), replace = T) # 'A' is HERE
plot(table(A))

set.seed(0)
B <- rbinom(50, 1, .5)  # 'B' is HERE
plot(table(B))

Solution

  • If we take the negation of 'B', it will be the same i.e. if we look the output of 'B', it has 0 values that takes the same position where it is 1 in A and viceversa

    identical(A, +!B)
    #[1] TRUE
    

    Or instead of doing the negation, create 'A', by doing the reverse i.e. 1:0

    set.seed(0)
    A <- sample(1:0, 50, prob = rep(.5, 2), replace = TRUE)
    identical(A, B)
    #[1] TRUE