Seeing How R Works
To end this overview of the R language, I wanted to share a few functions that are convenient for seeing how R works. As you may recall, R expressions are R objects. This means that it is possible to parse expressions in R, or partially evaluate expressions in R, and see how R interprets them. This can be very useful for learning how R works or for debugging R code.
As noted above, the R interpreter goes through several steps when evaluating statements. The first step is to parse a statement, changing it into proper functional form. It is possible to view the R interpreter to see how a given expression is evaluated. As an example, let’s use the same R code fragment that we used in The R Interpreter:
> if (x > 1) "orange" else "apple"
[1] "apple"
To show how this expression is parsed, we can use the quote()
function. This function will parse its
argument but not evaluate it. By calling quote
, an R expression returns a “language”
object:
> typeof(quote(if (x > 1) "orange" else "apple"))
[1] "language"
Unfortunately, the print
function
for language objects is not very informative:
> quote(if (x > 1) "orange" else "apple")
if (x > 1) "orange" else "apple"
However, it is possible to convert a language object into a list. By displaying the language object as a list, it is possible to see how R evaluates an expression. This is the parse tree for the expression:
> as(quote(if (x > 1) "orange" else "apple"),"list")
[[1]]
`if`
[[2]]
x > 1
[[3]]
[1] "orange"
[[4]]
[1] "apple"
We ...
Get R in a Nutshell, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.