6

Do julia arrays support indexing with multiple ranges like the following

dat = Array(1:10)
# trying to get dat[[1:3, 6:8]] to result in
dat[[1,2,3,6,7,8]]

Looking for something that would be like the R equivalent dat[c(1:3, 6:8)]?

1 Answer 1

10

The direct equivalent of the R version is

v = 1:10
v[ [1:3; 6:8] ]

since ; is the concatenation operator:

julia> [1:3; 6:8]
6-element Array{Int64,1}:
 1
 2
 3
 6
 7
 8

You may also want to look at chain in the Iterators.jl package: https://github.com/JuliaLang/Iterators.jl

Sign up to request clarification or add additional context in comments.

5 Comments

The slight gotcha is that the concatenation creates a new intermediate array, which is why chain is probably more efficient if the objects are large.
Iterators.chain returns an iterable, not an index-able array type, so you won't be able to use it as an index. There are some lazy concatenation libraries registered, but I've not tried any of them (VirtualArrays, CatViews). In this case, though, I'd be very surprised if these lazy types were any faster. Allocation is pretty cheap, but indexing into lazy concatenations requires an indexing search or hashmap or some such.
But it's not clear to me why you shouldn't be able to index an array (as in the original question) using an arbitrary iterable?
While the allocating getindex does currently iterate over its indices, views need to index into indices. There's a whole host of other implementation issues, but it is slightly more possible now that some iterables can have a shape.
I guess I was thinking only about indexing into 1D arrays. Higher dimensions is certainly a different story.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.