<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/the-ghost-printer-behind-top-level-r-expressions/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://yihui.name/en/2017/06/top-level-r-expressions/"> English Blog on Yihui Xie | 谢益辉</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>For any developers who have ever written an S3 method for the <code>print()</code> function, they probably know what a <em>top-level</em> R expression means, but this is a very confusing concept to non-developers. I have to explain this every now and then, so I decided to write a short post about it.</p>
<p>Yesterday I saw <a rel="nofollow" href="https://github.com/rstudio/rmarkdown/issues/1069" target="_blank">a Github issue</a> in the <strong>rmarkdown</strong> repository, and you can see that there are still users confused by the fact that <strong>ggplot2</strong> plots are not rendered in certain cases. I have seen similar questions perhaps hundreds of times. Such questions have been answered in the R FAQ 7.22 “<a rel="nofollow" href="https://cran.rstudio.com/doc/FAQ/R-FAQ.html#Why-do-lattice_002ftrellis-graphics-not-work_003f" target="_blank">Why do lattice/trellis graphics not work?</a>”, but the answer didn’t explain the root reason in detail.</p>
<p><img alt="Inferno" src="https://i2.wp.com/slides.yihui.name/images/inferno.jpg?w=456&ssl=1" data-recalc-dims="1"></p>
<p>A top-level R expression is usually <em>implicitly printed</em>. Both words can cause confusion: printing is <em>implicit</em> so that you probably don’t consciously know it, and <em>printing</em> means the <code>print()</code> function is called on the object returned by the expression. For example, when you type <code>1 + 1</code> in the R console, and press Enter/Return, what actually happens is <code>print(2)</code>, where <code>2</code> is the value returned by <code>1 + 1</code>.</p>
<p>The reason that you create a <code>ggplot()</code> object in your R console and it shows up after you press Enter is that <strong>ggplot2</strong> has defined a <code>print.ggplot</code> method on such objects. <code>ggplot()</code> does not actually create the plot – it only creates a <code>ggplot</code> object. It is <em>the print method</em> that actually creates the plot in a graphical device (as a <em>side-effect</em>).</p>
<p>Expressions nested in other expressions are not top-level expressions. For example, in a <code>for</code> loop, ggplot objects or <a rel="nofollow" href="http://htmlwidgets.org/" target="_blank">HTML widgets</a> or <code>knitr::kable()</code> cannot be displayed because they are not printed, unless you <em>explicitly</em> <code>print()</code> them.</p>
<p>Top-level R expressions are not always printed. They are not printed if they are marked as <em>invisible</em>. For example, if you run <code>invisible(1 + 1)</code> in the R console, you won’t see any value printed.</p>
<p>Many R functions return invisible values wrapped in the <code>invisible()</code> function. I want to show a few functions that you may have never recognized: <code>if</code>, <code>(</code>, and assignment operators such as <code>=</code> and <code>&lt;-</code> are all functions. Let’s start from the assignment operator:</p>
<pre><code>library(ggplot2)
p = ggplot(mpg, aes(cty, hwy)) + geom_point()
</code></pre>
<p>This creates a ggplot object but you do not see the plot even though this is a top-level expression, and that is because the assignment operator <code>=</code> returns the value <em>invisibly</em>. If you type <code>p</code> in the console later, you will see the plot since <code>p</code> is implicitly printed.</p>
<p>You can force a top-level expression to be visible (hence printed) by wrapping it in <code>()</code>, e.g., <code>(invisible(1 + 1))</code> will be printed, and so will the ggplot object below:</p>
<pre><code>library(ggplot2)
(p = ggplot(mpg, aes(cty, hwy)) + geom_point())
</code></pre>
<p>The <code>if</code> function returns the value of a last expression depending on the condition. For example, <code>if (TRUE) A else B</code> returns <code>A</code>, and <code>if (FALSE) {A} else {B; C}</code> returns <code>C</code>. With that in mind, you will understand why the ggplot object is not displayed in the <code>if</code> statement below:</p>
<pre><code>library(ggplot2)
if (TRUE) {
  ggplot(mpg, aes(cty, hwy)) + geom_point()
  1 + 1  # the value of this expression is returned (and printed)
}
</code></pre>
<p>Note <code>for</code>, <code>while</code>, and <code>repeat</code> loops always return an invisible <code>NULL</code>, so nothing will be printed automatically, including the last expression in the loop, e.g.,</p>
<pre><code>library(ggplot2)
for (i in 1:10) {
  ggplot(mpg, aes(cty, hwy)) + geom_point()
}
</code></pre>
<p>However, base R graphics is a different animal. All base R graphics functions will create plots no matter if they are called in top-level R expressions. For example, this will create 10 plots:</p>
<pre><code>for (i in 1:10) {
  plot(rnorm(100))
}
</code></pre>
<p>WAT?</p>
<p><img alt="Dog WAT" src="https://i1.wp.com/slides.yihui.name/gif/dog-wat.gif?w=456&ssl=1" data-recalc-dims="1"></p>
<p>WAT!</p>
<p><img alt="Darth Vader WAT" src="https://i1.wp.com/cdn.shopify.com/s/files/1/0070/7032/files/darth_wat_grande.jpg?w=456" data-recalc-dims="1"></p>
<p>Lastly, there is a function <code>withVisible()</code> that can tell you whether an expression returns a visible value or not, e.g.,</p>
<pre><code>withVisible(1 + 1)
# $value
# [1] 2
# 
# $visible
# [1] TRUE

withVisible({x = 1 + 1})  # assignment in {}
# $value
# [1] 2
# 
# $visible
# [1] FALSE
</code></pre>
<p>I hope you could remember the “ghost printer” the next time you run any R code in your R console or R Markdown or any <strong>knitr</strong> documents.</p>
<p> </p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://yihui.name/en/2017/06/top-level-r-expressions/"> English Blog on Yihui Xie | 谢益辉</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...

	<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/CSNAA-2e7YY" height="1"></a></div>