12

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?

Xizam
  • 699
  • 7
  • 21

2 Answers2

12

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 either if (condition) expression or if (condition) expression else expression. Likewise, the syntax for subsetting in R is obj[args…]. That is, ] is simply a syntactic element and it has no semantic equivalent, no corresponding function (same as else).

To make this perhaps even clearer:

  • [ and ] are syntactic elements in R that delimit a subsetting expression.
  • By contrast, `[` (note the backticks!) is a function that implements the subsetting operation.
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 2
    Another way to think of it is that `]` is used by R's parser to identify where the call to `[` ends. – Benjamin Jan 09 '17 at 13:14
  • That is what I assumed but wanted to check up on, since a couple of lines lines above this example the following quote was placed:“To understand computations in R, two slogans are helpful: Everything that exists is an object. Everything that happens is a function call." — John Chambers – Xizam Jan 09 '17 at 13:16
  • Ah, So this means that ] by and of itself is not a syntatical element, only when in the combination [...], where it refers to the primitive function` `[` `(in backticks)? – Xizam Jan 09 '17 at 13:18
  • @Xizam Yes, exactly. And the Chambers quote is still accurate: `]` isn’t something “that happens”, nor is it something that “exists” (at least not in R’s semantics). It’s simply syntactic sugar. In the same vein, comments are neither objects nor functions: they only exist in R’s code representation, not in its semantics. – Konrad Rudolph Jan 09 '17 at 13:18
  • @KonradRudolph Excellent, understood. Thanks! – Xizam Jan 09 '17 at 13:22
0

Somehow though, I was expecting ] to be a syntactical element, by default: indexing from the end. So I define it myself in my code:

 "]" <- function(x,y) if (y <= length(x)) x[length(x)+1-y] else NA

With the given example, then:

sapply(x, "]", 1)
[1]  3  9 12
sapply(x, "]", 2)
[1]  2  8 11
dojuba
  • 2,199
  • 1
  • 18
  • 16
  • 1
    Looks a bit like (but not identical to) `tail`. Not sure I like the use of symbols instead of expressive names for functions. – Konrad Rudolph Jan 09 '17 at 17:06