How to Weight and Random Sample in Julia
Overview
The usage of the function sample()
which serves a similar role to R’s sample()
or Python package numpy’s random.choice()
, and the Weights
function in Julia.
Code 1
using StatsBase
items = 0:5
weights = 0:5
sample(items, Weights(weights))
# With replacement
my_samps = sample(items, Weights(weights), 10)
# Without replacement
my_samps = sample(items, Weights(weights), 2, replace=false)
Execution Result
julia> using StatsBase
julia> items = 0:5
0:5
julia> weights = 0:5
0:5
julia> sample(items, Weights(weights))
5
julia> # With replacement
julia> my_samps = sample(items, Weights(weights), 10)
10-element Array{Int64,1}:
4
3
2
1
3
3
5
5
2
2
julia> # Without replacement
julia> my_samps = sample(items, Weights(weights), 2, replace=false)
2-element Array{Int64,1}:
4
5
Environment
- OS: Windows
- julia: v1.5.0