Skip to content

Commit

Permalink
Allow weighted means with arbitrary eltype (#476)
Browse files Browse the repository at this point in the history
PR 442 introduced a restriction of the input element type to be <:Number,
which means that the method doesn't get chosen by dispatch for e.g. inputs
with missing values. This leads to bizarre behavior, as it dispatches to a
nonsensical method where the array is treated as a function.
  • Loading branch information
ararslan committed Mar 5, 2019
1 parent 24a80ca commit 1823086
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/weights.jl
Expand Up @@ -466,11 +466,11 @@ w = rand(n)
mean(x, weights(w))
```
"""
mean(A::AbstractArray{T}, w::AbstractWeights{W};
dims::Union{Nothing,Int}=nothing) where {T<:Number,W<:Real} = _mean(A, w, dims)
_mean(A::AbstractArray{T}, w::AbstractWeights{W}, dims::Nothing) where {T<:Number,W<:Real} =
mean(A::AbstractArray, w::AbstractWeights; dims::Union{Nothing,Int}=nothing) =
_mean(A, w, dims)
_mean(A::AbstractArray, w::AbstractWeights, dims::Nothing) =
sum(A, w) / sum(w)
_mean(A::AbstractArray{T}, w::AbstractWeights{W}, dims::Int) where {T<:Number,W<:Real} =
_mean(A::AbstractArray{T}, w::AbstractWeights{W}, dims::Int) where {T,W} =
_mean!(similar(A, wmeantype(T, W), Base.reduced_indices(axes(A), dims)), A, w, dims)


Expand Down
4 changes: 4 additions & 0 deletions test/weights.jl
Expand Up @@ -443,4 +443,8 @@ end
@test median(data, f(wt)) quantile(data, f(wt), 0.5) atol = 1e-5
end

@testset "Mismatched eltypes" begin
@test round(mean(Union{Int,Missing}[1,2], weights([1,2])), digits=3) 1.667
end

end # @testset StatsBase.Weights

0 comments on commit 1823086

Please sign in to comment.