Skip to content

Commit

Permalink
Support filter for SkipMissing-wrapped arrays
Browse files Browse the repository at this point in the history
See discussion in issue 31188.
  • Loading branch information
ararslan committed Mar 2, 2019
1 parent 2ca7d83 commit 6b4394d
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
1 change: 1 addition & 0 deletions NEWS.md
Expand Up @@ -43,6 +43,7 @@ Standard library changes
* `hasmethod` can now check for matching keyword argument names ([#30712]).
* `startswith` and `endswith` now accept a `Regex` for the second argument ([#29790]).
* `retry` supports arbitrary callable objects ([#30382]).
* `filter` now supports `SkipMissing`-wrapped arrays ([#31233]).
* A no-argument construct to `Ptr{T}` has been added which constructs a null pointer ([#30919])

#### LinearAlgebra
Expand Down
31 changes: 31 additions & 0 deletions base/missing.jl
Expand Up @@ -328,6 +328,37 @@ mapreduce_impl(f, op, A::SkipMissing, ifirst::Integer, ilast::Integer) =
end
end

"""
filter(f, itr::SkipMissing{<:AbstractArray})
Return a 1-dimensional array similar to that wrapped by the given `SkipMissing` iterator
but with all missing elements and those for which `f` returns `false` removed.
!!! compat "Julia 1.2"
This method requires Julia 1.2 or later.
# Examples
```jldoctest
julia> x = [1 2; missing 4]
2×2 Array{Union{Missing, Int64},2}:
1 2
missing 4
julia> filter(isodd, skipmissing(x))
1-element Array{Int64,1}:
1
```
"""
function filter(f, itr::SkipMissing{<:AbstractArray})
y = similar(itr.x, eltype(itr), 0)
for xi in itr.x
if xi !== missing && f(xi)
push!(y, xi)
end
end
y
end

"""
coalesce(x, y...)
Expand Down
9 changes: 9 additions & 0 deletions test/missing.jl
Expand Up @@ -469,6 +469,15 @@ end
@test_throws ArgumentError mapreduce(x -> x/2, +, itr)
end
end

@testset "filter" begin
allmiss = Vector{Union{Int,Missing}}(missing, 10)
@test filter(isodd, allmiss) == Vector{Int}()
twod1 = [1.0f0 missing; 3.0f0 missing]
@test filter(x->x > 0, skipmissing(twod1)) == Float32[1.0f0, 3.0f0]
twod2 = [1.0f0 2.0f0; 3.0f0 4.0f0]
@test filter(x->x > 0, skipmissing(twod2)) == reshape(twod2, (4,))
end
end

@testset "coalesce" begin
Expand Down

0 comments on commit 6b4394d

Please sign in to comment.