Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 606
Xizam Avatar asked Jan 09 '17 13:01

Xizam


1 Answers

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.
like image 106
Konrad Rudolph Avatar answered Nov 15 '22 18:11

Konrad Rudolph