0
votes

I would like to create a logical vector that has 10 rows, with each row randomly assigned either TRUE or FALSE. However, I want there to only be 3 FALSE and 7 TRUE.

Example of desired outcome (logical vector with three randomly assigned FALSE entries and 7 randomly assigned TRUE entries):

> vector
 [1] "TRUE"  "TRUE"  "FALSE" "TRUE"  "FALSE" "FALSE" "TRUE" "TRUE" "TRUE" 
[10] "TRUE" 

I can create a logical vector of size 10 that has TRUE or FALSE, but I don't know how to specify I want three FALSE entries and 7 TRUE entries.

vector <- sample(x = c("TRUE","FALSE"), size = 10, replace = TRUE)

This produces:

> train
 [1] "TRUE"  "TRUE"  "FALSE" "TRUE"  "FALSE" "FALSE" "FALSE" "FALSE" "FALSE"
[10] "TRUE" 

Which has the incorrect number of TRUE and FALSE entries (4 TRUE and 6 FALSE).

3
sample( c( rep(TRUE,7), rep(FALSE,3) ) ) ? - Wimpel

3 Answers

1
votes

Like Wimpel and PKumar combined:

vector <- sample(c(rep(TRUE, 7), rep(FALSE, 3)), 10 ,replace = F)
1
votes

If you just want to shuffle the positions of TRUE and FALSE, you can try the code below

res <- (v <- c(rep(TRUE, 7), rep(FALSE, 3)))[sample(seq(v))]

where sample(seq(v)) generates random positions from 1 to length(v)

1
votes

You can try this:

Approach1 : Use prob parameter to give proportions for sample you select along with replace=TRUE in sample command. sample command doesn't guarantee the exact value of proportion, but for larger sample size it may give approximate proportions

x <- c(TRUE, FALSE)
sample(x,10 ,replace = TRUE, prob=c(.7, .3))

Approach2: For a perfect proportion:

rep(c(TRUE, FALSE), times= c(7,3)) ## In case you want to have perfect proportion
    #if someone wanted to randomly shuffle then one cas use:
     rep(c(TRUE, FALSE), times= c(7,3))[order(runif(10))]

Output:

> sample(x,10 ,replace = T, prob=c(.7, .3))
 [1] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE
 [8]  TRUE  TRUE  TRUE

Output:

rep(c(TRUE, FALSE), times= c(7,3))[order(runif(10))]
  [1]  TRUE FALSE  TRUE  TRUE  TRUE FALSE  TRUE
  [8]  TRUE  TRUE FALSE