MayaGans
MayaGans

Reputation: 1845

list indexing with [[ vs [ and NULL

If I create a list

mylist = list()
mylist[1] <- "test"

[[ returns:

mylist[[1]]
# [1] "test"

[ returns:

mylist[1]
# [[1]]
# [1] "test"

But in the case where

mylist = list()

why does

mylist[1]

Result in

[[1]]
NULL

But

mylist[[1]] 

Does not return NULL it -- returns an error?

Error in mylist[[1]] : subscript out of bounds

Upvotes: 2

Views: 187

Answers (1)

BetterCallMe
BetterCallMe

Reputation: 768

Suppose we have a list as:

mylist  = list()
mylist[[1]] = c(1,2,3)
mylist[[2]] = c(4,5,6)

In the concept of list we can say mylist has two layers which can be accessed by [[ and there element can be accessed by[ like:

mylist[[1]][2]  

In your case mylist has no layer so when you do mylist[1] R defaultly access first layer and says there are no elements in the first layer of mylist and returns NULL but when you do mylist[[1]] R says Out of Bounds because the first layer of mylist has been called and there is no layer at all. That's why R throws error in [[ case.

Upvotes: 1

Related Questions