Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index Array without Elements

Tags:

julia

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.)

like image 370
Georgery Avatar asked Oct 10 '20 12:10

Georgery


People also ask

Can an array have empty elements?

The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not. An empty array will have 0 elements inside of it.

Can we search array value without index number?

When searching an array without an index, use the status (on or off) of the resulting indicators to determine whether a particular element is present in the array. Searching an array without an index can be used for validity checking of input data to determine if a field is in a list of array elements.

Can you index an array with string?

Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object.


Video Answer


2 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).

like image 197
Bogumił Kamiński Avatar answered Sep 20 '22 17:09

Bogumił Kamiński


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
like image 36
Przemyslaw Szufel Avatar answered Sep 21 '22 17:09

Przemyslaw Szufel