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

Asked

Viewed 823 times

6

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

2 answers

13

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

Imagine that saleiro be it:

saleiro

So saleiro[1], results in:

subset de saleiro

And, in turn, with saleiro[[1]] we have:

inserir a descrição da imagem aqui

That is, in short the [ preserves the shape of the outer object, even when selecting only one object, while the [[ extracts the same element, disregarding the "bark" of the external object.

  • 3

    I didn’t know, good!

12


I’ll start by quoting the R’s documentation:

The Most Important Distinction between [, [[ and $ is that the [
can select more than one element whereas the other two select a
single element.

Translation Google Translate:

The most important distinction between [, [[ and $ is that the [ can select
more than one element, while the other two select a single
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 only one element is extracted, 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

A matrix is a vector with a dimension attribute, so there is no difference either.

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 class objects "list" can no longer be used interchangeably [ or [[. The first extracts a sub-list (possibly with multiple 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 as class objects "data.frame" 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"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.