I have a input vector vi with boolean values. I want to take a random sample of size n from the vector where the value is true, so the final vector vf has these properties
-
The lengths of the vectors are equal
length(vf) == length(v0) -
vfhasntrue values
n==sum(vf) -
The true values in
vfcannot be more than those inv0
n <= sum(v0) -
All the true values in
vfare also true invi
The vectors represents a selection of rows in a data frame, and this implements a stratified sample. So far I figured out how to use which() to get the row numbers, to use sample() to get a random sample, but the last part is recreating the boolean vector. There is probably a more elegant way?
For example:
n <- 1
v0 <- c(T,T,F,F)
vf <- c(T,F,F,F)
Here’s one solution: