If `[` is a function for subsetting in R, what is `]`?

1.5k views Asked by At

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?

2

There are 2 answers

5
Konrad Rudolph On BEST ANSWER

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.
1
dojuba On

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