I'm reading the advanced R introduction by Hadley Wickham, where he states that [ (and +, -, {, etc) are functions, so that [ can be used in this manner
> x <- list(1:3, 4:9, 10:12)
> sapply(x, "[", 2)
[1] 2 5 11
Which is perfectly fine and understandable. But if [ is the function required to subset, does ] have another use rather than a syntactical one?
I found that:
> `]`
Error: object ']' not found
so I assume there is no other use for it?
This is the fundamental difference between syntax and semantics. Semantics require that — in R — things like subsetting and
if
etc are functions. That’s why R defines functions`[`
,`if`
etc.And then there’s syntax. And R’s syntax dictates that the syntax for
if
is eitherif (condition) expression
orif (condition) expression else expression
. Likewise, the syntax for subsetting in R isobj[args…]
. That is,]
is simply a syntactic element and it has no semantic equivalent, no corresponding function (same aselse
).To make this perhaps even clearer:
[
and]
are syntactic elements in R that delimit a subsetting expression.`[`
(note the backticks!) is a function that implements the subsetting operation.