Julia's Negative/Complement Indexing like R

Viewed 1846

Is there a functionality in Julia that's similar to R's negative indexing? In R, the code would be similar to:

x = 1:10
inds = c(1, 5, 7)
x[-inds]

[1]  2  3  4  6  8  9 10

I've found this to be extremely useful in numerous situations, especially for things such as sampling indices to create a testing/training set, but also for subindexing an array to exclude certain rows. So I am hoping there's something simple in Julia that can do the same.

2 Answers

This is similar to @Colin T Bower's answer and also only uses base Julia. Afraid it is not as elegant as your R example.

julia> minus(indx, x) = setdiff(1:length(x), indx)
minus (generic function with 1 method)

julia> x = collect(1:10)
10-element Array{Int64,1}:
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10

julia> inds = [1, 5, 7]
3-element Array{Int64,1}:
 1
 5
 7

julia> x[minus(inds, x)]
7-element Array{Int64,1}:
  2
  3
  4
  6
  8
  9
 10
Related