Julia: Finding values larger than 0 in vector with missing

Ric*_*ard 1 missing-data julia

I'm fairly new to Julia and as a Matlab/R User I find it, for the most part, really nice to work with.

However, I'm a little confused by the missing values and how to work with them.

Let's say I have a vector:

a=[missing -1 2 3 -12] #Julia
a=[NaN -1 2 3 -12] #Matlab
Run Code Online (Sandbox Code Playgroud)

In Matlab I would just do the following to find the values below 0

a(a<0)
Run Code Online (Sandbox Code Playgroud)

which gives me

-1 -12
Run Code Online (Sandbox Code Playgroud)

The same unfortunately doesn't work in Julia and when I try

a[a.<0]
Run Code Online (Sandbox Code Playgroud)

in Julia I just get the following error

ERROR: ArgumentError: unable to check bounds for indices of type Missing
Run Code Online (Sandbox Code Playgroud)

I also tried the following

a[findall(skipmissing(a).<0)]
Run Code Online (Sandbox Code Playgroud)

which gives me

missing
3
Run Code Online (Sandbox Code Playgroud)

since, of course, I skipped the missing value in the findall-function. I'm pretty sure there is an easy and logical way to do this, but I don't seem to be able to find it.

Can someone please show me the way?

Best, Richard

Bog*_*ski 7

这是最简单的方法:

julia> a=[missing -1 2 3 -12]
1×5 Array{Union{Missing, Int64},2}:
 missing  -1  2  3  -12

julia> a[isless.(a, 0)]
2-element Array{Union{Missing, Int64},1}:
  -1
 -12
Run Code Online (Sandbox Code Playgroud)

这使用了一个事实,该事实missing被认为比任何数字都大isless

另一种写法:

julia> filter(x -> isless(x, 0), a)
2-element Array{Union{Missing, Int64},1}:
  -1
 -12
Run Code Online (Sandbox Code Playgroud)

现在,为了避免使用此特殊技巧,isless可以执行以下操作(使用coalesce可用于安全处理missing值的通用方法):

julia> a[coalesce.(a .< 0, false)]
2-element Array{Union{Missing, Int64},1}:
  -1
 -12
Run Code Online (Sandbox Code Playgroud)

要么

julia> filter(x -> coalesce(x < 0, false), a)
2-element Array{Union{Missing, Int64},1}:
  -1
 -12
Run Code Online (Sandbox Code Playgroud)

最终,您可以更明确地显示如下:

julia> filter(x -> !ismissing(x) && x < 0, a)
2-element Array{Union{Missing, Int64},1}:
  -1
 -12
Run Code Online (Sandbox Code Playgroud)

要么

julia> [v for v in a if !ismissing(v) && v < 0]
2-element Array{Int64,1}:
  -1
 -12
Run Code Online (Sandbox Code Playgroud)

(您也可以在上面的示例中使用理解语法)