Reputation: 370
Is it possible with the new version of Julia (1.3.0) to add "missing" + 1 and get a "1" instead of a "missing"?? I want to sum two columns from an Array and skip the missings, but keeping the same number of rows. Thanks!
Upvotes: 2
Views: 244
Reputation: 13800
This is a somewhat unusual treatment of missing
- if I understand you correctly you want missing
to behave like a zero if added to another number, and like missing
when added to another missing
. Given that this is a bit unusual, I would just write it out explicitly:
julia> a = [1, missing, missing]; b = [2, 1, missing];
julia> ifelse.(ismissing.(a) .& ismissing.(b), missing, coalesce.(a, 0) .+ coalesce.(b, 0))
3-element Vector{Union{Missing, Int64}}:
3
1
missing
coalesce
replaces missing
with 0 in the above, but the result of that addition is only used if either of the two values being added is nonmissing.
Upvotes: 1
Reputation: 69949
Given your requirements I would recommend you to define your own custom addition that would implement the rule you want:
julia> ⨨(::Missing, ::Missing) = missing
⨨ (generic function with 1 method)
julia> ⨨(x, ::Missing) = x
⨨ (generic function with 2 methods)
julia> ⨨(::Missing, x) = x
⨨ (generic function with 3 methods)
julia> ⨨(x, y) = x + y
⨨ (generic function with 4 methods)
julia> [1, 2, missing, missing] .⨨ [10, missing, 30, missing]
4-element Vector{Union{Missing, Int64}}:
11
2
30
missing
In my example ⨨
can be typed by \plustrif<tab>
(you could use any other symbol that is accepted as operator instead).
This is the most efficient way to achieve what you want.
Upvotes: 1