Skip to content

Fix NaN and missing detection in quantile() #72

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/Statistics.jl
Original file line number Diff line number Diff line change
Expand Up @@ -960,8 +960,10 @@ function _quantilesort!(v::AbstractArray, sorted::Bool, minp::Real, maxp::Real)
# only need to perform partial sort
sort!(v, 1, lv, Base.Sort.PartialQuickSort(lo:hi), Base.Sort.Forward)
end
ismissing(v[end]) && throw(ArgumentError("quantiles are undefined in presence of missing values"))
isnan(v[end]) && throw(ArgumentError("quantiles are undefined in presence of NaNs"))
if (sorted && (ismissing(v[end]) || (v[end] isa Number && isnan(v[end])))) ||
any(x -> ismissing(x) || (x isa Number && isnan(x)), v)
throw(ArgumentError("quantiles are undefined in presence of NaNs or missing values"))
end
return v
end

Expand Down
11 changes: 9 additions & 2 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -557,8 +557,15 @@ end
@test quantile(Any[1, Float16(2), 3], Float16(0.5)) isa Float16
@test quantile(Any[1, big(2), 3], Float16(0.5)) isa BigFloat

@test_throws ArgumentError quantile([1, missing], 0.5)
@test_throws ArgumentError quantile([1, NaN], 0.5)
# Need a large vector to actually check consequences of partial sorting
x = rand(50)
for sorted in (false, true)
x[10] = NaN
@test_throws ArgumentError quantile(x, 0.5, sorted=sorted)
x = Vector{Union{Float64, Missing}}(x)
x[10] = missing
@test_throws ArgumentError quantile(x, 0.5, sorted=sorted)
end
@test quantile(skipmissing([1, missing, 2]), 0.5) === 1.5
@test quantile([1], 0.5) === 1.0

Expand Down