Skip to content

sample with UnitWeights and replace=false throws "no field values" error #950

@hughselway

Description

@hughselway

Using sample with no replacements and unit weights throws an error, seeming to assume the weights object will have values.

I'm trying to sample in a way agnostic to whether FrequencyWeights or UnitWeights are passed.

Minimal reproducible example

using StatsBase
sample(1:5, uweights(5), 3, replace=false)

I would expect this to be equivalent to sample(1:5, 3, replace=false) but instead it throws this error:

ERROR: type UnitWeights has no field values
Stacktrace:
 [1] getproperty
   @ ./Base.jl:49 [inlined]
 [2] efraimidis_aexpj_wsample_norep!(rng::Random.TaskLocalRNG, a::UnitRange{…}, wv::UnitWeights{…}, x::Vector{…}; ordered::Bool)
   @ StatsBase ~/.julia/packages/StatsBase/xgoZ5/src/sampling.jl:869
 [3] efraimidis_aexpj_wsample_norep!
   @ ~/.julia/packages/StatsBase/xgoZ5/src/sampling.jl:848 [inlined]
 [4] sample!(rng::Random.TaskLocalRNG, a::UnitRange{…}, wv::UnitWeights{…}, x::Vector{…}; replace::Bool, ordered::Bool)
   @ StatsBase ~/.julia/packages/StatsBase/xgoZ5/src/sampling.jl:944
 [5] sample!
   @ ~/.julia/packages/StatsBase/xgoZ5/src/sampling.jl:918 [inlined]
 [6] sample
   @ ~/.julia/packages/StatsBase/xgoZ5/src/sampling.jl:952 [inlined]
 [7] #sample#220
   @ ~/.julia/packages/StatsBase/xgoZ5/src/sampling.jl:955 [inlined]
 [8] top-level scope
   @ REPL[2]:1
Some type information was truncated. Use `show(err)` to see complete types.

Current workaround
I can condition on typeof the weights variable until there's an internal fix.

Versions
Julia 1.11.3
StatsBase v0.34.4

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions