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?

> 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.

buhtz
  • 10,774
  • 18
  • 76
  • 149
  • 1
    There is no 0 index in R. It starts from 1 – Sotos May 04 '22 at 09:09
  • See the `a[0]` in my MWE. If this is not an "index" than please answer and explain what it is. – buhtz May 04 '22 at 09:10
  • 1
    The [dupe](https://stackoverflow.com/questions/10610775/why-does-x0-return-a-zero-length-vector) states that `0` indices get "ignored" which might be a bit vague. Actually it behaves as if `0` is coerced to `NULL`, try `a[c(0, 1)]`, `a[c(NULL, 1)]`, and `a[0]`, `a[NULL]`. – jay.sf May 04 '22 at 13:33

2 Answers2

2

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
Pedro Alencar
  • 1,049
  • 7
  • 20
1

There is no index 0, as you see when you use the [[ operator, which returns the element of the list at index 0, which does not exist.

However, when you use the [ operator a list, it returns the a list containing the object at that index. Using your example, look at the difference in what is returned using each operator.

a <- list(1, 2, 3)
a[[1]] # 1
class(a[[1]]) # numeric (i.e. a vector)

a[1]
# [[1]]
# [1] 1
class(a[1]) # list

When you run a[0], you get a list containing the object at index 0, which does not exist, i.e. an empty list().

SamR
  • 8,826
  • 3
  • 11
  • 33