Skip to content
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

Support filter for SkipMissing-wrapped arrays #31235

Merged
merged 1 commit into from
Mar 7, 2019
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
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
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 ([#31235]).
* 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
Original file line number Diff line number Diff line change
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 vector similar to the array 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
Original file line number Diff line number Diff line change
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 isempty(filter(isodd, skipmissing(allmiss))::Vector{Int})
twod1 = [1.0f0 missing; 3.0f0 missing]
@test filter(x->x > 0, skipmissing(twod1))::Vector{Float32} == [1, 3]
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