5

I am wondering why the not operator isn't working with array broadcasting/element-wise operations. For example, if I enter

 x = Array{Any}([1,2,3,4,missing,6])
 !ismissing.(x)

I get an error ERROR: MethodError: no method matching !(::BitArray{1})

but if I try ismissing.(x) it works fine,

ismissing.(x)
#out > 6-element BitArray{1}: 0 0 0 0 1 0

and typing without the broadcasting works as a whole as well (one output for the entire array)

!ismissing(x)
#out > True

So I am wondering if there is a possibility to get a similar result as using the "!" operator.

imantha
  • 2,676
  • 4
  • 23
  • 46
  • 4
    I advise you to *not* wrap the array in an `Array{Any}` constructor. That forces the array to have eltype `Any` which is slow. Instead, allow Julia to figure out the type, like this: `x = [1,2,3,4,missing,6]`. This will have eltype `Union{Missing, Int}`, which is very efficiently handled by the compiler. In general, it's best to leave handling of eltypes to the compiler, unless you have some specific reason to enforce your own limitations. In this case you will get a 2x speedup from the `ismissing` call. – DNF Feb 19 '21 at 15:03

1 Answers1

13

You need to also broadcast ! to each element:

julia> x = Array{Any}([1,2,3,4,missing,6]);

julia> .!(ismissing.(x)) # the . comes before operators (!, +, -, etc)
6-element BitVector:
 1
 1
 1
 1
 0
 1

For this specific case you can instead negate the function before broadcasting:

julia> (!ismissing).(x)
6-element BitVector:
 1
 1
 1
 1
 0
 1
fredrikekre
  • 10,413
  • 1
  • 32
  • 47