Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sample n times with replacement in Julia

Tags:

sample

julia

I'm trying to draw n -- say, 10 for simplicity -- samples from an array in Julia. Using the function wsample, ndraws below gives me what I wanted

using Distributions
population = [ 1, 10 ]
weights = [ .4, .6 ]
population_idx = wsample( population, weights, 10 ) # i.e. population indices
ndraws = population[ population_idx ]

I'm using Julia 0.2. Is there a way to do the same thing without the indices? In R for instance, we have

ndraws <- sample( population, size = 10, replace = TRUE, prob = weights )

The docs here suggests there is i.e. doing this

ndraws = wsample( population, weights, 10 )

should give me, err, exactly what I want? Note too, that in the docs, the argument name for number of draws is n but looking in the source code of sample.jl, it refers to k.

like image 571
vathymut Avatar asked May 24 '14 05:05

vathymut


1 Answers

wsample(population, weights, n) returns n samples from population (not the indexes). This is in the Distributions package.

For example,

julia> using Distributions
julia> wsample(["a", "b"], [0.3, 0.7], 10)
10-element Array{ASCIIString,1}:
 "a"
 "b"
 "b"
 "b"
 "b"
 "b"
 "b"
 "b"
 "a"
 "b"

If what you want is to draw indexes, you can use 1:k as the population, for example, wsample(1:k, weights, n).

like image 156
lindahua Avatar answered Sep 17 '22 20:09

lindahua