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

2

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?

Dumbbell answered 9/1, 2017 at 13:3 Comment(0)
M
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.
Mercurio answered 9/1, 2017 at 13:13 Comment(5)
Another way to think of it is that ] is used by R's parser to identify where the call to [ ends.Scevo
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 ChambersDumbbell
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)?Dumbbell
@Dumbbell 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.Mercurio
@KonradRudolph Excellent, understood. Thanks!Dumbbell
S
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
Stereobate answered 9/1, 2017 at 13:33 Comment(1)
Looks a bit like (but not identical to) tail. Not sure I like the use of symbols instead of expressive names for functions.Mercurio

© 2022 - 2024 — McMap. All rights reserved.