3

Suppose I want to create a sample of N elements chosen from [1,2,3] such that 1, 2 and 3 will be represented with weights 0.4,0.4 and 0.2 respectively. How would I do this.

I know how to do it in R without using loops:

mySample <- sample(c(1,2,3),size = 100,replace=T,prob = c(.4,.4,.2)) 
1

1 Answer 1

3

You can generate a random number in [0,1) then if it is in [0,.4) pick "1", else if it is in [.4,.8) pick "2" and else pick "3". the code is:

from random import random; N = 10; elements = [1,2,3]; weights = [.4, .4 , .2]; samples = range(N); r = 0; temp = 0; for i in range(10): r = random(); temp = 0; for j in range(len(elements)): temp += weights[j]; if(temp>r): samples[i] = elements[j]; break; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.