Julia数组的列联表



考虑一个只有0和1的(m x n)矩阵,其中m可能很大。

julia> rand([0, 1], 5, 3)
5×3 Array{Int64,2}:
0  1  1
0  0  0
0  1  1
1  0  0
1  0  1

是否有一种有效的方法来计算出现的次数并跟踪每个唯一行的索引?

例如,上面的第一行出现两次,在索引1和3处。我正在尝试建立一种列联表。

感谢

这是仅基于Julia Base提供的功能的方法之一:

julia> x = rand([0, 1], 20, 3)
20×3 Matrix{Int64}:
1  0  1
1  1  1
0  0  0
1  0  0
0  0  1
1  0  1
0  0  0
1  0  1
0  0  0
0  0  1
1  1  0
0  1  1
0  1  1
1  0  0
0  0  0
0  0  0
0  0  1
0  1  0
1  1  0
1  0  0
julia> d = Dict()
Dict{Any, Any}()
julia> for (i, r) in enumerate(eachrow(x))
push!(get!(d, r, Int[]), i)
end
julia> d
Dict{Any, Any} with 8 entries:
[1, 1, 1] => [2]
[0, 0, 0] => [3, 7, 9, 15, 16]
[0, 0, 1] => [5, 10, 17]
[1, 1, 0] => [11, 19]
[1, 0, 0] => [4, 14, 20]
[0, 1, 1] => [12, 13]
[1, 0, 1] => [1, 6, 8]
[0, 1, 0] => [18]

,现在使用SplitApplyCombine。杰包:

julia> using SplitApplyCombine
julia> group(i -> view(x, i, :), axes(x, 1))
8-element Dictionaries.Dictionary{Any, Vector{Int64}}
[1, 0, 1] │ [1, 6, 8]
[1, 1, 1] │ [2]
[0, 0, 0] │ [3, 7, 9, 15, 16]
[1, 0, 0] │ [4, 14, 20]
[0, 0, 1] │ [5, 10, 17]
[1, 1, 0] │ [11, 19]
[0, 1, 1] │ [12, 13]
[0, 1, 0] │ [18]

最新更新