Stream: helpdesk (published)

Topic: Second argument of mode


view this post on Zulip Júlio Hoffimann (Sep 26 2021 at 20:49):

Can you please give an example of a valid range in the mode docstring? https://juliastats.org/StatsBase.jl/v0.20/scalarstats.html#Mode-and-Modes-1

What it means to pass a range to the mode function?

view this post on Zulip Sundar R (Sep 26 2021 at 22:32):

Looking at the source, it looks like values outside the given Range are ignored for the calculation of mode.

view this post on Zulip Sundar R (Sep 26 2021 at 22:33):

So mode(arr, 2:4) should be semantically the same as mode(filter(n -> 2 <= n <= 4, arr)) (but presumably more efficient)

view this post on Zulip Júlio Hoffimann (Sep 27 2021 at 10:07):

Did you try running the code? It doesn't work with simple ranges:

julia> mode(rand(10), 0.5:1.0)
ERROR: MethodError: no method matching mode(::Vector{Float64}, ::StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}})
Closest candidates are:
  mode(::AbstractVector{T} where T, ::AbstractWeights{T, T1, V} where {T1<:Real, V<:AbstractVector{T1}}) where T<:Real at /home/juliohm/.julia/packages/StatsBase/PGTj8/src/scalarstats.jl:164
  mode(::Any) at /home/juliohm/.julia/packages/StatsBase/PGTj8/src/scalarstats.jl:111

view this post on Zulip Sebastian Pfitzner (Sep 27 2021 at 10:14):

Sure it does, but the range argument is only implemented for integers:

julia> arr = rand(1:10, 10)
10-element Vector{Int64}:
  3
  6
  6
  1
  5
 10
  5
  1
  3
  6

julia> mode(arr, 4:6)
6

view this post on Zulip Sebastian Pfitzner (Sep 27 2021 at 10:14):

The docstring just fails to mention that

view this post on Zulip Júlio Hoffimann (Sep 27 2021 at 14:59):

Even the first argument must be integer ?

view this post on Zulip Sundar R (Sep 27 2021 at 17:40):

For the two argument call, yes:

function mode(a::AbstractArray{T}, r::UnitRange{T}) where T<:Integer

I'm not sure why this range argument exists in the first place (when for eg. it doesn't exist for mean), and now also not sure why it's only defined for Integer values and ranges. Maybe it's worth opening an issue for, at least to clarify things and maybe document them better.

view this post on Zulip Júlio Hoffimann (Sep 27 2021 at 23:22):

Yes it doesn't seem like a natural choice of arguments to me either.


Last updated: Oct 02 2023 at 04:34 UTC