Exclude elements of Array based on index (Julia)

Viewed 7281

What is the most natural way to filter an array by index in Julia? The simplest example would be to leave off the kth element:

A = [1,2,3,4,5,6,7,8]
k = 4

[getindex(A, i) for i = 1:8 if i != k]

The above works but seems verbose compared to the simple A[-k] available in R. What's the cleanest way to perform this simple task?

5 Answers

Not as terse as the R equivalent, but fairly readable:

A[1:end .!= k]

More importantly, this can be used in multidimensional arrays too, e.g.

B[  1:end .!= i,   1:end .!= j,   1:end .!= k  ]

Have a look at deleteat!. Examples:

julia> A = [1,2,3,4,5,6,7,8]; k = 4;

julia> deleteat!(A, k)
7-element Array{Int64,1}:
 1
 2
 3
 5
 6
 7
 8

julia> A = [1,2,3,4,5,6,7,8]; k = 2:2:8;

julia> deleteat!(A, k)
4-element Array{Int64,1}:
 1
 3
 5
 7

The simplest way is to use "Not".

julia> using InvertedIndices # use ] add InvertedIndices if not installed

julia> A = [1,2,3,4,5,6,7,8]

julia> k = 4;

julia> A[Not(k)]
7-element Array{Int64,1}:
 1
 2
 3
 5
 6
 7
 8

You may use filter in conjunction with eachindex

julia> A = collect(1:8); println(A)        
[1, 2, 3, 4, 5, 6, 7, 8]                   

julia> A[ filter(x->!(x in [5,6]) && x>2, eachindex(A)) ]
4-element Array{Int64,1}:
 3
 4
 7
 8

If you apply a filter to each dimension of the array, you will need to replace eachindex(A) by indices(A,n) where n is the appropriate dimension, e.g

B[ filter(x->!(x  in [5,6])&&x>2, indices(B,1)), filter(x->x>3, indices(B,2)) ]
Related