Vectorize replace with Vector of String raises DimensionMismatch

Hello,

I’m trying to replace coma with point in the following Vector of String

julia> a = ["0,309042 46,586349 111,4", "0,309042 46,586349 111,1", "0,309042 46,586349 111,3"]
3-element Array{String,1}:
 "0,309042 46,586349 111,4"
 "0,309042 46,586349 111,1"
 "0,309042 46,586349 111,3"

julia> replace(a, ","=>".")
3-element Array{String,1}:
 "0,309042 46,586349 111,4"
 "0,309042 46,586349 111,1"
 "0,309042 46,586349 111,3"

julia> replace.(a, ","=>".")
ERROR: DimensionMismatch("arrays could not be broadcast to a common size")
Stacktrace:
 [1] _bcs1 at ./broadcast.jl:485 [inlined]
 [2] _bcs at ./broadcast.jl:479 [inlined]
 [3] broadcast_shape at ./broadcast.jl:473 [inlined]
 [4] combine_axes at ./broadcast.jl:468 [inlined]
 [5] instantiate at ./broadcast.jl:256 [inlined]
 [6] materialize(::Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{1},Nothing,typeof(replace),Tuple{Array{String,1},Array{String,1}}}) at ./broadcast.jl:798
 [7] top-level scope at REPL[42]:1

But it doesn’t seem to be possible.

Any idea why it’s failling?

Using list comprehension can be a workaround

[replace(c, ","=>".") for c in a]

but I would like to understand why broadcasting doesn’t work and raises

ERROR: DimensionMismatch("arrays could not be broadcast to a common size")

Kind regards

Since Pairs are also iterable you need to “protect” the pair from broadcasting with Ref, which makes it behave like a scalar instead:

julia> a = ["0,309042 46,586349 111,4", "0,309042 46,586349 111,1", "0,309042 46,586349 111,3"];

julia> replace.(a, Ref(","=>"."))
3-element Array{String,1}:
 "0.309042 46.586349 111.4"
 "0.309042 46.586349 111.1"
 "0.309042 46.586349 111.3"

Note, however, that in Julia 1.3 and later Pairs are treated as scalars by default, so the Ref is not needed there, see https://github.com/JuliaLang/julia/pull/32209.

3 Likes