What is the difference between [] and [[]] in R?

8

I just used [ ] to define the position of an element in a vector or array ( [ ] , [,] , [, ,] ...), but how does [[ ]] work?     

asked by anonymous 06.12.2018 / 18:28

2 answers

10

I'll start by citing the R documentation:

  

The most important distinction between [ , [[ and $ is that the [
  can select more than one element while the other two select
  single element.

Translation Google Translate:

  

The most important distinction between [ , [[ and $ is that [ can select
  more than one element, while the other two select a single element   element.

This can be seen in the simplest case, the case of vectors.

x <- 1:10

x[4:6]
#[1] 4 5 6

x[[4:6]]
#Error in x[[4:6]] : 
#  attempt to select more than one element in vectorIndex

There may, however, be another important difference, which I will explain. When you extract only one element, the result of the operation may be different. This difference does not exist in the case of vectors but exists in the case of lists.

identical(x[4], x[[4]])
#[1] TRUE

An array is a vector with a dimension attribute, so there is no difference.

mat <- matrix(1:10, nrow = 5, byrow = TRUE)
mat[4]
#[1] 7

mat[[4]]
#[1] 7

identical(mat[4], mat[[4]])
#[1] TRUE

But in the case of objects of class "list" you can no longer use [ or [[ . The first one extracts a sub-list (possibly with several vectors), the second a vector from the list.

lst <- list(A = 1:6, B = letters[1:10], C = rnorm(3))

lst[1]
#$A
#[1] 1 2 3 4 5 6

lst[[1]]
#[1] 1 2 3 4 5 6

identical(lst[1], lst[[1]])
#[1] FALSE

And since class "data.frame" objects are lists, there is also a big difference. [ extracts sub-df's (possibly with multiple column vectors) and [[ extracts a single vector.

dat <- data.frame(A = letters[1:10], 
                  X = 1:10,
                  stringsAsFactors = FALSE)

dat[1]
#   A
#1  a
#2  b
#3  c
#4  d
#5  e
#6  f
#7  g
#8  h
#9  i
#10 j

dat[[1]]
#[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
    
06.12.2018 / 19:42
9

In addition to Rui's comments, I share the metaphor created in R for data science :

Imagine that saleiro is:

Thensaleiro[1],resultsin:

And,inturn,withsaleiro[[1]]wehave:

Inotherwords,inaddition,[preservestheshapeoftheouterobject,evenwhenselectingonlyoneobject,while[[extractsthesameelement,neglectingtheoutershell's"shell."

    
06.12.2018 / 20:49