Site icon R-bloggers

R-Markdown and Knitr Tutorial (Part 2)

[This article was first published on Modern Data » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

In our last post we quickly went over how to create a new R-Markdown document and embed a Plotly graph in it. In this post we’ll get into more details around how to control code output using chunk options.

As shown in our previous post, for the embedded R code to be evaluated, it’ll need to be written inside a code-chunk as shown below.

  ```{r Code Chunk, chunk options here...}
  # R code here...
  ``` 

Chunk options

Knitr provides a lot of ways to control the output that shows up in the final document. We’ll highlight a few common ones.

Echo

echo allows control over visibility of the actual R code in a chunk. Set it to FALSE to hide the R code from showing up. Note that the code chunk will still be evaluated and any outputs mirrored in the final document. Use eval = FALSE if you do not need a code chunk to be evaluated at all.

  ```{r Code Chunk, echo = FALSE}
  # R code will be evaluated but not shown in the final HTML document
  # Useful when only plots / charts / text output needs to be shown and not the
  # code that generated it...
  ``` 

Message

Notice how if you use include() in a code chunk, messages from the R console are mirrored in the final document as well? By default, when knitr evaluates a code chunk, it mirrors any messages that show up in the console as well. We can turn that off using message = FALSE.

  ```{r Code Chunk, message = FALSE}
  # R code
  # Messages from R-Console will not show up in final document
  ``` 

With message = TRUE

library(plotly)
## Loading required package: ggplot2
## 
## Attaching package: 'plotly'
## 
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## 
## The following object is masked from 'package:graphics':
## 
##     layout

With message = FALSE

library(plotly)

Results

Controls the mirroring of output when a code chunk is evaluated. This includes text output as well as charts / graphs. Four values can be assigned: (see http://yihui.name/knitr/options/ for more details)

  • markup – markup output using output hook
  • asis – raw output
  • hold – shows output after all code is evaluated
  • hide – no output is shown
  ```{r Code Chunk, results = 'markup'}
  # R code will be evaluated but not shown in the final HTML document
  # Useful when only plots / charts / text output needs to be shown and not the
  # code that generated it...
  ``` 

With results = ‘markup’

str(mtcars)
## 'data.frame':    32 obs. of  11 variables:
##  $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
##  $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
##  $ disp: num  160 160 108 258 360 ...
##  $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
##  $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
##  $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
##  $ qsec: num  16.5 17 18.6 19.4 17 ...
##  $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
##  $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
##  $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
##  $ carb: num  4 4 1 1 2 1 4 2 2 4 ...

With results = ‘asis’

str(mtcars)

‘data.frame’: 32 obs. of 11 variables: $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 … $ cyl : num 6 6 4 6 8 6 8 4 4 6 … $ disp: num 160 160 108 258 360 … $ hp : num 110 110 93 110 175 105 245 62 95 123 … $ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 … $ wt : num 2.62 2.88 2.32 3.21 3.44 … $ qsec: num 16.5 17 18.6 19.4 17 … $ vs : num 0 0 1 1 0 1 0 1 1 1 … $ am : num 1 1 1 0 0 0 0 0 0 0 … $ gear: num 4 4 4 3 3 3 3 4 4 4 … $ carb: num 4 4 1 1 2 1 4 2 2 4 …

With results = ‘hide’

str(mtcars)

Figure related options

The set of fig.* options allow control over how charts / graphs are shown in the final document. Below are some examples. For more details see http://yihui.name/knitr/options/

Width and Height

Use fig.width and fig.height. Note that units are in inches by default

Small

  ```{r Code Chunk, fig.width = 2, fig.height = 2}
  df <- diamonds[sample(1:nrow(diamonds), size = 2000),]

  plot_ly(df, x = x, y = price, mode = "markers", color = cut, size = z) %>%
  layout(title = "Diamonds")
  ``` 


BIG

  ```{r Code Chunk, fig.width = 8, fig.height = 8}
  df <- diamonds[sample(1:nrow(diamonds), size = 2000),]

  plot_ly(df, x = x, y = price, mode = "markers", color = cut, size = z) %>%
  layout(title = "Diamonds")
  ``` 

Alignment

Figure alignment for figures using base graphics and or ggplot2 is easy. Simply use fig.align = 'left' / 'right' / 'center'

  ```{r Code Chunk, fig.align = 'right'}
  df <- diamonds[sample(1:nrow(diamonds), size = 2000),]

  plot_ly(df, x = x, y = price, mode = "markers", color = cut, size = z) %>%
  layout(title = "Diamonds")
  ``` 

But for figures generated using the plot_ly() function, we’ll need to use the <div> tag. Use the following as an example.

<div style = "float: right"> 

  ```{r Code Chunk}
  df <- diamonds[sample(1:nrow(diamonds), size = 2000),]

  plot_ly(df, x = x, y = price, mode = "markers", color = cut, size = z) %>%
  layout(title = "Diamonds")
  ``` 
</div>

IFrame

<iframe> allows Plotly charts available in your Plotly account to be embedded in a R-Markdown document. Simply point the src argument to the chart’s ‘embed’ link as provided by Plotly. See http://help.plot.ly/embed-graphs-in-websites/ for more details.

<iframe width="450" height="400" frameborder="0" scrolling="no" src="https://plot.ly/~riddhiman/47.embed"></iframe>  

Note that using <iframe> makes the HTML file more blog friendly.

To leave a comment for the author, please follow the link and comment on their blog: Modern Data » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.