Ifelse type result

Dear J wizard—I want to code my own basic recode (without CategoricalArrays, which has very deep dependencies, via DataStream into … ). easy me thinks.

julia> recode( v::Vector, p::Pair )=   ( T= Vector{Union{typeof(p[1]),typeof(p[2])}}; v=T(v); ifelse.( isequal.(v,p[1]) , p[2], v ))
recode (generic function with 1 method)

and now

julia> recode( [1.0,2.0,3.0], 2.0 => NaN ) . ## perfect
3-element Array{Float64,1}:
   1.0
 NaN
   3.0

julia> using Missings

julia> recode( [1.0,2.0,3.0], 2.0 => missing ) . ## not so perfect.
3-element Array{Any,1}:
 1.0
  missing
 3.0

how do I get the Any to be the Union?

This just works as you wrote it on version 0.7. On 0.6, you could use an explicitly typed comprehension instead:

julia> recode( v::Vector, p::Pair )= Union{typeof(p[1]),typeof(p[2])}[ifelse(isequal(x, p[1]), p[2], x) for x in v]
recode (generic function with 1 method)

julia> using Missings

julia> recode( [1.0,2.0,3.0], 2.0 => missing )
3-element Array{Union{Float64, Missings.Missing},1}:
 1.0
  missing
 3.0
1 Like

FWIW, replace does what you need on Julia 0.7.

2 Likes

thx. will note it in the cookbook. regards, /iaw