Several of the answers to this question suggest that the best way to extract a subset from a list is to use something like sapply(mylist, "[", y)
. I found this rather disturbing, because I have never seen anything to suggest that we can use "[" as if it's a function. Where is this documented? I checked ?'[['
for my version, 3.6.3, but I can't see any reference to this functionality in that documentation.
Asked
Active
Viewed 57 times
2

J. Mini
- 1,868
- 1
- 9
- 38
-
3All operators in R are functions. This is documented in the language definition: https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Operators – Roland Oct 07 '20 at 11:31
-
1@Roland ```'+'(3,4)``` works? Great. I didn't expect to be able to make my R code look like Lisp. – J. Mini Oct 07 '20 at 11:34
-
R's design was inspired by Scheme. – Roland Oct 07 '20 at 11:41
-
@J.Mini `'+'(3,4)` does not work. You have to use backticks. – bcarlsen Oct 07 '20 at 13:23
-
@bcarlsen You are mistaken. Try it. – Roland Oct 07 '20 at 13:25
-
I am wrong! but from reading `?Quotes` this seems kind of horrible. `[...] under many circumstances single or double quotes can be used (as a character constant will often be converted to a name)` is not the kind of reassuring stability you want in a language spec – bcarlsen Oct 07 '20 at 13:30
-
@bcarlsen Out of context, this quote sounds worse than it is. It's all very stable. The wording is used because there are exceptions where you can't use single or double quotes. The next sentence points to such an exception. It similar to the difference between `<-` and `=`. Mostly, they are interchangeable, except within expressions that are function calls. – Roland Oct 07 '20 at 14:13
-
I highly recommend getting a (free) copy of "The R-Inferno" . https://www.burns-stat.com/pages/Tutor/R_inferno.pdf – Carl Witthoft Oct 07 '20 at 17:45
1 Answers
3
All operators in R are functions. This is documented in the language definition:
https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Operators
Like the other operators, indexing is really done by functions, and one could have used
`[`(x, 2)
instead ofx[2]
.

Roland
- 127,288
- 10
- 191
- 288
-
And for real fun, look at the source code for the package `sos` , function --- well, operator `???` – Carl Witthoft Oct 07 '20 at 17:46