0

I have a named numb vector of probabilities, like this

Vector elements

Like you can see, the sum of this vector elements it's 1, I have to generate a random number between 0 and 1 and get the element of this vector that don't overcome this random number, for example:

The random number generate: 0.01 I will get the water element because water it's between 0.09 and 0.11. I attach an graphic example

Example

I don't know how to get the element of this probability.

Dragg
  • 83
  • 2
  • 11
  • 2
    Welcome to SO. Please avoid posting pictures of data. Have a [look at this link](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) and post a reproducible example. This will make it easier for others to help you. – Sotos Jun 19 '17 at 20:33

1 Answers1

0

I am not going to type in all of your data, so I will use a comparable, small example:

set.seed(2017)
probabilidad = runif(5)
probabilidad= probabilidad/sum(probabilidad)
names(probabilidad) = LETTERS[1:5]
probabilidad
         A          B          C          D          E 
0.30918062 0.17969799 0.15695684 0.09655216 0.25761238 
sum(probabilidad)
[1] 1

We can use cumsum to set up a vector to make the choices you want. But cumsum will give the upper bounds for the regions and we want the lower bounds, so we adjust the output a little.

Test = c(0, cumsum(probabilidad)[-length(probabilidad)])
names(Test) = names(probabilidad)
Test
        A         B         C         D         E 
0.0000000 0.2533938 0.5129561 0.5922145 0.8222417 

Now you can easily test random numbers against the distribution.

(Selector = runif(1))
[1] 0.5190959
names(probabilidad)[max(which(Selector > Test))]
[1] "C"
G5W
  • 36,531
  • 10
  • 47
  • 80