Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is in index 0 of an R list if they usually start with index 1?

Coming from Python I try to get deeper into the habits and design principals of R. So this is not a homework question.

It seems usual that list() starting with index 1 and not 0.

> a = list(1,2,3)
> a[[1]]
[1] 1

But what is at index 0?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

> a[[0]]
Error in a[[0]] : 
  attempt to select less than one element in get1index <real>
> a[0]
list()

I know that there is a difference about [] and [[]]. I don’t fully understand the difference or the design principals behind it.

Is there an PEP equivalent for R to read about design decisions?

EDIT: The "duplicate" question doesn’t fit my question and there is also no accepted answer. The answers in my question IMHO are much better.

>Solution :

When you use [[]] you are extracting the element from the list. Therefore, you will have a[[1]] = 1, but an error for a[[0]]] because there is no such element.

When you use [] in a list you are slicing (sub-setting) it. That is why a[1] = [[1]] 1 and a[0] returns an empty element (there is no zeroth list).

This is made clear by checking the class of the outputs.

class(a[[1]]) # -> numeric
class(a[1]) # -> list
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading