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 in 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" ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access