Search code examples
samplejulia

Sample n times with replacement in 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.


Solution

  • 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).