You simpliy need N samples from a bernouli (ie, 0 or 1) distribution, where N
is the number of values in H/L. You then use the sampling to pick from H or L respectively. using ifelse
ensures the "parallel selection" you require.
set.seed(1)
N <- length(H)
HorL <- rbinom(N, 1, 0.5)
# the select
results <- ifelse(HorL, H, L)
results
# [1] 6 7 3 4 10
This all wraps up as a nice one liner:
ifelse( rbinom(H, 1, 0.5), H, L)
from @Arun:
A (relatively) faster way of implementing this (removing the need for ifelse
) would be:
idx <- which(!as.logical(rbinom(H, 1, 0.5)))
vv <- H
vv[idx] <- L[idx]
EXPLANATION
@Gabriel, The idea is that you are selecting from one of two options. You can effectively flip a coin and, if heads, select from H, if tails, select from L. This is a Bernouli Distribution, a more general form is the Binomial distribution. R has a facility to offer random numbers of just such a fashion.
Thus we ask R for N
many of these, then select from H or L accordingly.
The "select from .. " part is the R
trickery.
Notice that we can think of
0, 1
asTRUE, FALSE
orA, B
, etc.Using the
ifelse
approach should be somewhat self explanatory. If it is TRUE, select from one source, if it is FALSE, select from the other.
Arun's approach is more creative. His approach uses the same "flip a coin" mechanism for choosing between sets, but has the benefit of speed. (We are speaking nanoseconds, but still). His approach essentially says:
- Start with one group, say H.
- Flip a coin.
- Whenever the coin is Tails, replace that element of H with the same indexed element of L. (Notice that the "same index" aspect is what you are refering to as "parallel selection")