r - vectorized parallel selection that's random? -


i have 2 vectors "h" , "l" have 200 numeric values. want create third vector called "hl" contains 200 random samples h , l. however, them selected in parallel, same way pmin , 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 random pick each 'column' shown above, e.g:  hl <- c(6,2,8,4,10) 

is there way of doing without using loop?

any advice appreciated thanks

you simpliy need n samples bernouli (ie, 0 or 1) distribution, n number of values in h/l. use sampling pick h or l respectively. using ifelse ensures "parallel selection" require.

set.seed(1) n <- length(h) horl <- rbinom(n, 1, 0.5)  # select results <- ifelse(horl, h, l)  results # [1]  6  7  3  4 10 

this wraps nice 1 liner:

ifelse( rbinom(h, 1, 0.5), h, l) 

from @arun: (relatively) faster way of implementing (removing need ifelse) be:

idx <- which(!as.logical(rbinom(h, 1, 0.5))) vv <- h vv[idx] <- l[idx] 

explanation

@gabriel, idea selecting 1 of 2 options. can flip coin and, if heads, select h, if tails, select l. bernouli distribution, more general form binomial distribution. r has facility offer random numbers of such fashion.

thus ask r n many of these, select h or l accordingly.

the "select .. " part r trickery.

  • notice can think of 0, 1 true, false or a, b, etc.

  • using ifelse approach should self explanatory. if true, select 1 source, if false, select other.

arun's approach more creative. approach uses same "flip coin" mechanism choosing between sets, has benefit of speed. (we speaking nanoseconds, still). approach says:

  • start 1 group, h.
  • flip coin.
  • whenever coin tails, replace element of h same indexed element of l. (notice "same index" aspect refering "parallel selection")

Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -