Index Array without Elements

Viewed 120

I have a vector

a = Vector(1:4)

[1, 2, 3, 4]

and I want to index it to all elements but the third to get

[1, 2, 4]

in R you could do a[-3]. What do you do in Julia?

(Eventually I want to loop through all the elements and compare each of them to the rest - maybe this is relevant.)

3 Answers

This use case is a common one and is covered by the InvertedIndices.jl package. If you install it then you can run:

julia> using InvertedIndices

julia> a = 1:4
1:4

julia> a[Not(3)]
3-element Array{Int64,1}:
 1
 2
 4

Also some packages (like DataFrames.jl) automatically load this package (so if you e.g. use DataFrames.jl you do not have to install and load InvertedIndices.jl separately).

The Julia syntax will be unfortunately more verbose than those of R:

julia> a[1:end .!== 3]
3-element Array{Int64,1}:
 1
 2
 4

Another option is to mutate a:

julia> deleteat!(a,3)
3-element Array{Int64,1}:
 1
 2
 4

If your data is within a DataFrame than you can get a nicer syntax:

julia> df = DataFrame(a=1:4);

julia> df[Not(3),:]
3×1 DataFrame
│ Row │ a     │
│     │ Int64 │
├─────┼───────┤
│ 1   │ 1     │
│ 2   │ 2     │
│ 3   │ 4     │

and when DataFrames is imported Not will also work with a Vector:

julia> a[Not(3)]
3-element Array{Int64,1}:
 1
 2
 4

I have not seen

julia> a[1:end .≠ 3]
3-element Array{Int64,1}:
 1
 2
 4

or

julia> a[eachindex(a) .≠ 3]
3-element Array{Int64,1}:
 1
 2
 4

mentioned, but maybe there is a good reason?


EDIT: I was wrong, the first one is actually the same as Bogumil's first answer except !== has been replaced with ≠

Related