I have two vectors "H" and "L" that have 200 numeric values. I want to create a third vector called "HL" that contains 200 random samples from H and L. However, I would like them to be selected in parallel, the same way the pmin and pmax function do.
Simplified example:
H <- 1:5
L <- 6:10
# rbind(H,L)
# [,1] [,2] [,3] [,4] [,5]
# H 1 2 3 4 5
# L 6 7 8 9 10
# intended result is then a random pick from each 'column' shown above, e.g:
HL <- c(6,2,8,4,10)
Is there a way of doing this without using a loop?
Any advice would be much appreciated Thanks
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
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]
@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 as TRUE, FALSE or A, 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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With