-1

I know this is a newbie question, but I am trying to understand the difference between the [[ ]] and $ in accessing elements in a list. Are there special cases where I have advantages to use one over the other?

I think to understand that you can use [[ to select any single element and the returned object will be determined by the type of the element, whereas [ returns a list object of the selected element or even a list with multiple elements. On the other hand when using $ to reference an element in a list the returned type is not a list but the actual value.

Is this korrect? Are there any occasions where I must use [[ ]] or $?

Thank you for any help.

2 Answers2

1

You'd benefit from reading the list chapter of "R for Data Science".

Basically, you can use $ when the list elements have names:

mylist <- list(x = 1:3, y = 4:6)
names(mylist)
[1] "x" "y"

mylist$x
[1] 1 2 3

You can use [[]] for a named list as well as an unnamed list, if you like:

mylist[[1]]
[1] 1 2 3

But you can't use $ if the list elements are not named:

mylist <- list(1:3, 4:6)
names(mylist)
NULL

mylist$x
NULL

mylist[[1]]
[1] 1 2 3
neilfws
  • 32,751
  • 5
  • 50
  • 63
1

from the R language definiton (https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Indexing):

The form using $ applies to recursive objects such as lists and pairlists. It allows only a literal character string or a symbol as the index. That is, the index is not computable: for cases where you need to evaluate an expression to find the index, use x[[expr]].

For example:

my.list = list("a"=1 , "b"=2)
my.index = "b"
#this works
my.list[[my.index]]    
# this doesn't    
my.list$my.index
David Heckmann
  • 2,899
  • 2
  • 20
  • 29