Using '[' as a function
On 29/07/2010 6:18 PM, chipmaney wrote:
I am learning R, and instead of learning by rote, I am trying to better understand the language in order to improve my programming. So any "meta-information" on why the following code works would be greatly appreciated... I obtained this code to extract the first record from each of a series of vectors in a list:
example<- list(c(1,2),c(3,4),c(4,5))
[[1]] [1] 1 2 [[2]] [1] 3 4 [[3]] [1] 4 5
sapply(example,'[',1)
[1] 1 3 4 however, after perusing my book and the interweb, i remain puzzled about how '[' works as a function in sapply. -Why does R recognize '[' as a function?
Because it is a function.
-Why does it need the quotes?
Because sapply(example,[,1) would not be syntactically valid.
- How does the function know to use the optional(?) argument "1" as the index location?
Its definition is available by typing
`[`
and that shows it to be
.Primitive("[")
Primitive functions are all handled specially by the R evaluator. In
this case, you can look at the man page ?"[" which shows a variety of
different argument signatures that are possible. R will pass all
optional arguments to the function, which will then (in special case
code, because it's a primitive) will figure out which one of those
syntax patterns is what the user intended.
- Any other information linking this specific example to the broader R environment?
Primitive functions aren't the best place to start in understanding R, because by definition, they're all special cases. I'd suggest writing your own functions with a variety of argument signatures and passing them to sapply to see what happens. Duncan Murdoch
Any explanation of how this function works will be a small incremental gain in my understanding of R, so thanks in advance. Chipper