Omry Atia
Omry Atia

Reputation: 2443

Sample a number from 0 to 1 with uneven probabilities

I would like to sample a random number between 0 and 1, with an 90% probability to sample from 0-0.3 and 10% to sample between 0.3-1.

I tried the following:

0.9*runif(1, 0, 0.3) + 0.1*runif(1, 0.3, 1)

But that's not quite it: I will never get the number 0.8, for example.

Is there a simple way to do it in Base R?

Upvotes: 1

Views: 734

Answers (3)

Rui Barradas
Rui Barradas

Reputation: 76402

You can write a small function to do the job whenever you need it.

runif_probs <- function(n, p = 0.9, cutpoint = 0.3){
    ifelse(runif(n) <= p, runif(n, 0, cutpoint), runif(n, cutpoint, 1))
}

set.seed(8862)

which(runif_probs(100) > 0.8)
#[1] 38 62

Upvotes: 0

nicola
nicola

Reputation: 24480

Usually in R you want to do stuff in a vectorized way. So don't draw a number at the time, but draw all of them in one call (much faster). Here you can use sample to draw the higher extremum and the draw. Like this:

nsamples<-100000
res<-runif(nsamples,0,sample(c(0.03,1),nsamples,TRUE,prob=c(10,90)))
#just to check the result
hist(res)
#this should be around 0.127(=0.9*0.03+0.1*1) if correct
mean(res<0.03)

Upvotes: 0

tushaR
tushaR

Reputation: 3116

sample(c(runif(1,0,0.3),runif(1,0.3,1)),1,prob=c(0.9,0.1))

Upvotes: 4

Related Questions