Julia:如何有效计算`Vector{Union{T, Missing}}`中缺失的数量

xia*_*dai 4 julia

考虑

x = rand([missing, rand(Int, 100)...], 1_000_000)
Run Code Online (Sandbox Code Playgroud)

这产生typeof(x)= Array{Union{Missing, Int64},1}

计算 中缺失次数的最有效方法是x什么?

crs*_*nbr 6

最干净的方法可能只是

count(ismissing, x)
Run Code Online (Sandbox Code Playgroud)

简单、易记、快速

由于您要求“最有效”的方式,让我给出一些基准测试结果。它比@xiaodai 的答案略快,并且与简单的循环实现一样快:

julia> @btime count($ismissing,$x);
  278.499 ?s (0 allocations: 0 bytes)

julia> @btime mapreduce($ismissing, $+, $x);
  293.901 ?s (0 allocations: 0 bytes)

julia> @btime count_missing($x)
  278.499 ?s (0 allocations: 0 bytes)
Run Code Online (Sandbox Code Playgroud)

在哪里

julia> function count_missing(x)
           c = 0
           @inbounds for i in eachindex(x)
               if ismissing(x[i])
                   c += 1
               end
           end
           return c
       end
Run Code Online (Sandbox Code Playgroud)

免费抽象,按照您希望的方式进行。