1

The R documentation (as well as extensive R folklore) describes the different operators for extraction.

However, it appears that neither the documentation nor the folklore explain why it is that the use of different operators ( [ versus [[ ) can return identical results. Can someone provide an explanation? Note that I'm asking not why they can produce different results, but why they can sometimes produce an identical result. Why does x[2] (see below) evaluate identically to x[[2]]?

x <- c("a","b","c") ; x[2] ; x[[2]]
## [1] "b"
## [1] "b"
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • It will have an effect on a `list` or `data.frame`. Also, check the difference with `x[1:2]` and `x[[1:2]]` – akrun Jan 09 '21 at 18:54
  • I don't think this is a duplicate. The linked questions are focussed on the _differences_ between the two syntaxes, not why they're sometimes identical. Which is not (obviously) explicitly stated in the docs either. – MattB Jan 09 '21 at 22:09
  • 2
    The real answer (as far as I know) is that there is no distinction in R between a value (e.g. `3`) and a vector of length 1 (e.g. `c(3)`). `x[[2]]` should give you a value and `x[2]` should give you a vector of length 1. But these two things are identical. – MattB Jan 09 '21 at 22:13
  • @MattB, please post your comments as an answer ? – Ben Bolker Jan 09 '21 at 22:54

1 Answers1

2

There is no distinction in R between a value (e.g. 3) and a vector of length 1 (e.g. c(3)). x[[2]] should give you a value and x[2] should give you a vector of length 1. But these two things are identical.

MattB
  • 651
  • 3
  • 11
  • 1
    There is a difference: `x[2]` preserves the name if there is one, while this name is dropped with `x[[2]]`. Try `x <- c(a = 1, b = 2)`. – Stéphane Laurent Jan 10 '21 at 07:03