How to slice data from a middle index until the end without using `length` in R (like you can in python)?
RR Problem Overview
In python, I can slice the last four items from a five-item list (pull values from it) like so: mylist[1:]
(note, 0-based indexing). In R, it seems that not having something after the colon is an error. In both languages, I can put the last argument as the length of the list, but that's not always convenient (e.g. inline slicing: colnames(iris)[2:length(colnames(iris))]
).
Is there any such syntax in R?
R Solutions
Solution 1 - R
Well this is confusing coming from a python background, but mylist[-1]
seems to do the trick. The negative in this case can be read as "except," i.e. take everything except column 1. So colnames(iris)[-1]
works to grab all but the first item.
Oh, and to exclude more items, treat it as a range that is excluded, so colnames(iris)[-2:-4]
would keep only the first and all items after (and including) the fifth one.
For others coming from python, check out this nice slideshow comparing R to python.
Solution 2 - R
In R tail(mylist, -2)
, has the same effect as mylist[2:]
in Python.