13

In python lists can be sliced like this x[4:-1] to get from the fourth to the last element.

In R something similar can be accomplished for vectors with x[4:length(x)] and for multidimensional arrays with something like x[,,,,4:dim(x)[5],,,]. Is this more elegant syntax for array slicing for a particular dimension from an element in the middle to the last element?

Thanks

momeara
  • 1,341
  • 2
  • 17
  • 29
  • 3
    Actually in python, x[4:-1] will skip the last element. To include the last element you just need x[4:], which is equivalent to algoriffic's (1:10)[-(1:4)] in R. – signalseeker Jan 27 '10 at 13:56
  • 1
    Also one off at the front! In python x[4:-1] will get the fifth (not the fourth) to the penultimate element. – Epimetheus Aug 13 '15 at 15:29

2 Answers2

23

You could use the drop elements syntax:

> (1:10)[-(1:4)]
[1]  5  6  7  8  9 10
AnthonyF
  • 878
  • 1
  • 9
  • 12
7

In case you are interested in slicing the last n elements of the array then you could use:

x[seq(length=n, from=length(x), by=-1)] 
Xavier Guardiola
  • 2,699
  • 3
  • 19
  • 11