Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to slice data from a middle index until the end without using `length` in R (like you can in python)?

Tags:

r

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?

like image 841
Pat Avatar asked Feb 28 '13 04:02

Pat


People also ask

How do I slice an index in R?

To produce a vector slice between two indexes, we can use the colon operator ":". This can be convenient for situations involving large vectors. More information for the colon operator is available in the R documentation.

What does [- 1 :] mean in Python?

Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.

How do I slice a dataset in R?

There are various ways to slice data frame rows in R :Using Numeric Indexing. Using Name Indexing. Indexing using logical vectors.

What happen if you use out of range index with slicing?

The slicing operation doesn't raise an error if both your start and stop indices are larger than the sequence length. This is in contrast to simple indexing—if you index an element that is out of bounds, Python will throw an index out of bounds error. However, with slicing it simply returns an empty sequence.


1 Answers

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.

like image 125
Pat Avatar answered Sep 23 '22 06:09

Pat