180

So I want to insert a table AND a picture into R Markdown. In regular word document I can just easily insert a table (5 rows by 2 columns), and for the picture just copy and paste.

  1. How do I insert a 5 row by 2 column table (and also type stuff into them)(and also adjust the table in terms of the 2nd column being wider than the first)?

  2. How do I insert a picture? From my understanding, I should first save the picture as a png, then reference it into my document. Also, I want to automatically adjust the picture to the report, like not taking up more than a page, or less than a page.(Is there a way for me to adjust the size of the picture to my liking)?

  3. If anyone knows anything cool/formatting about R Markdown could you also let me know? I know that # makes a big title for a paragraph, and ** ** bolds things. Thats about all I know though!

Michael Harper
  • 14,721
  • 2
  • 60
  • 84
user3784616
  • 1,939
  • 3
  • 15
  • 10
  • see also http://stackoverflow.com/questions/15625990/how-to-set-size-for-local-image-using-knitr-for-markdown – baptiste Oct 31 '16 at 02:48

4 Answers4

207

Several sites provide reasonable cheat sheets or HOWTOs for tables and images. Top on my list are:

Pictures are very simple to use but do not offer the ability to adjust the image to fit the page (see Update, below). To adjust the image properties (size, resolution, colors, border, etc), you'll need some form of image editor. I find I can do everything I need with one of ImageMagick, GIMP, or InkScape, all free and open source.

To add a picture, use:

![Caption for the picture.](/path/to/image.png)

I know pandoc supports PNG and JPG, which should meet most of your needs.

You do have control over image size if you are creating it in R (e.g., a plot). This can be done either directly in the command to create the image or, even better, via options if you are using knitr (highly recommended ... check out chunk options, specifically under Plots).

I strongly recommend perusing these tutorials; markdown is very handy and has many features most people don't use on a regular basis but really like once they learn it. (SO is not necessarily the best place to ask questions that are answered very directly in these tutorials.)


Update, 2019-Aug-31

Some time ago, pandoc incorporated "link_attributes" for images (apparently in 2015, with commit jgm/pandoc#244cd56). "Resizing images" can be done directly. For example:

![unchanged image](foo.jpg)
![much-smaller image](foo.jpg){#id .class width=30 height=20px}
![half-size image](foo.jpg){#id .class width=50% height=50%}

The dimensions can be provided with no units (pixels assumed), or with "px, cm, mm, in, inch and %" (ref: https://pandoc.org/MANUAL.html, search for link_attributes).

(I'm not certain that CommonMark has implemented this, though there was a lengthy discussion.)

r2evans
  • 141,215
  • 6
  • 77
  • 149
  • If you're still reading this, about the picture. Can I open Rmarkdown file it again on another computer without the picture? Is the picture permanent once I add it to R? If not how to I make it permanent – user3784616 Aug 06 '14 at 21:07
  • 4
    The file is not permanent within the `.Rmd` file. If you "compile" it (using pandoc) to HTML, adding `--self-contained` will encode the image into the html file. PDF and Word files will have it as part of the file, so you will not need to include the actual PNG file when you send it out. Rmd files, however, required you to include the image file manually. – r2evans Aug 06 '14 at 21:11
  • how does it work..? I can't even seem to add the picture.. So basically the picture is named "Employment Rates" and it's in a file folder called "Summary". The location of the file is C:\Users\Paul\Desktop\Summary. So the code I wrote is ![Employment Rates.](C:/Users/Paul/Desktop.Summary.png) and it doesn't work – user3784616 Aug 06 '14 at 21:34
  • can you give me an example of how to use the --self-contained? So when I save it as a word doc it will permanent have the image? I'm still a little bit confused – user3784616 Aug 06 '14 at 21:35
  • 1
    Better yet, using it within the YAML header of the Rmd is more straight-forward (and the default, apparently). Here's the reference: [rmarkdown at rstudio](http://rmarkdown.rstudio.com/html_document_format.html). Over 1/3 of the way down is a section on "Document Dependencies" which addresses its use. – r2evans Aug 06 '14 at 22:13
  • How would I make the picture a clickable link? – Zach May 18 '15 at 15:47
  • @Zach, I believe you'll need to resort to insert raw HTML into your document, which should pass through just fine. A clickable link isn't immediately obvious in other output formats; for example, in a DOCX, how would you make an image clickable? To where would it link? How would you have to make this happen *manually*? Perhaps this is loosely related to [issue 813](https://github.com/jgm/pandoc/issues/813) on pandoc-discuss. – r2evans May 18 '15 at 16:15
  • "To add a picture, use: ![Caption for the picture.](/path/to/image.png)" just produces an error. – slap-a-da-bias Mar 20 '18 at 19:17
  • @slap-a-da-bias, you're going to need to be more specific than that. I just tried it (successfully) with `output: pdf_document`, `word_document`, and `html_document`, and it worked. I suggest if there's an error, it might be due to path differences (absolute vs relative), back-slashing (os?), or something else. If you're still having problems, it might be worth opening a new question on SO than trying to fix within comments, but if I see it I'll give it a look. – r2evans Mar 20 '18 at 20:05
150

Update: since the answer from @r2evans, it is much easier to insert images into R Markdown and control the size of the image.

Images

The bookdown book does a great job of explaining that the best way to include images is by using include_graphics(). For example, a full width image can be printed with a caption below:

```{r pressure, echo=FALSE, fig.cap="A caption", out.width = '100%'}
knitr::include_graphics("temp.png")
```

The reason this method is better than the pandoc approach ![your image](path/to/image):

  • It automatically changes the command based on the output format (HTML/PDF/Word)
  • The same syntax can be used to the size of the plot (fig.width), the output width in the report (out.width), add captions (fig.cap) etc.
  • It uses the best graphical devices for the output. This means PDF images remain high resolution.

Tables

knitr::kable() is the best way to include tables in an R Markdown report as explained fully here. Again, this function is intelligent in automatically selecting the correct formatting for the output selected.

```{r table}
knitr::kable(mtcars[1:5,, 1:5], caption = "A table caption")
```

If you want to make your own simple tables in R Markdown and are using R Studio, you can check out the insert_table package. It provides a tidy graphical interface for making tables.

Achieving custom styling of the table column width is beyond the scope of knitr, but the kableExtra package has been written to help achieve this: https://cran.r-project.org/web/packages/kableExtra/index.html

Style Tips

The R Markdown cheat sheet is still the best place to learn about most the basic syntax you can use.

If you are looking for potential extensions to the formatting, the bookdown package is also worth exploring. It provides the ability to cross-reference, create special headers and more: https://bookdown.org/yihui/bookdown/markdown-extensions-by-bookdown.html

Michael Harper
  • 14,721
  • 2
  • 60
  • 84
  • Do you know how to lock the image location in place? Right now it's very hard to predict where it will appear when I compile it. – wolfsatthedoor Jun 01 '19 at 06:28
  • 1
    I was wrestling with the `![image caption](\path\to\image.png)` trying to insert an image in R Markdown rendered .docx, but failed mysteriously, until I saw your `knitr::include_graphics()` solution today. Thank you so much! – elarry Oct 03 '19 at 08:57
  • How to reference the image? – Aliton Oliveira Nov 05 '20 at 14:53
10

When it comes to inserting a picture, r2evans's suggestion of ![Caption for the picture.](/path/to/image.png) can be problematic if PDF output is required.

The knitr function include_graphics knitr::include_graphics('/path/to/image.png') is a more portable alternative that will generate, on your behalf, the markdown that is most appropriate to the output format that you are generating.

Martin Smith
  • 3,687
  • 1
  • 24
  • 51
  • Curious ... why is the use of `![caption](path/to/image.png)` problematic if PDF output is required? Perhaps this answer is outdated (as was my original answer), but I've been using this in PDF output for a couple of years at least. – r2evans Jan 13 '20 at 21:14
  • 1
    If I recall correctly, the relative path is taken as relative to the R working directory, which might not always correspond to the directory that the file is in. – Martin Smith May 26 '21 at 09:35
  • Certainly ... but that would apply to `include_graphics("path/to/image.png")` as well, wouldn't it? Granted, `path/to/` is not the same as `/path/to/`, but the portability of document rendering can be controlled by the use of working directories and/or normalized paths. Good point. – r2evans May 26 '21 at 13:16
5

In March I made a deck presentation in slidify, Rmarkdown with impress.js which is a cool 3D framework. My index.Rmdheader looks like

---
title       : French TER (regional train) monthly regularity
subtitle    : since January 2013
author      : brigasnuncamais
job         : Business Intelligence / Data Scientist consultant
framework   : impressjs     # {io2012, html5slides, shower, dzslides, ...}
highlighter : highlight.js  # {highlight.js, prettify, highlight}
hitheme     : tomorrow      # 
widgets     : []            # {mathjax, quiz, bootstrap}
mode        : selfcontained # {standalone, draft}
knit        : slidify::knit2slides

subdirs are:

/assets /css    /impress-demo.css
        /fig    /unnamed-chunk-1-1.png (generated by included R code)
        /img    /SS850452.png (my image used as background)
        /js     /impress.js
        /layouts/custbg.html # content:--- layout: slide --- {{{ slide.html }}}
        /libraries  /frameworks /impressjs
                                /io2012
                    /highlighters   /highlight.js
                                    /impress.js
index.Rmd

A slide with image in background code snippet would be in my .Rmd:

<div id="bg">
  <img src="assets/img/SS850452.png" alt="">
</div>  

Some issues appeared since I last worked on it (photos are no more in background, text it too large on my R plot) but it works fine on my local. Troubles come when I run it on RPubs.

M--
  • 25,431
  • 8
  • 61
  • 93
brigasnuncamais
  • 127
  • 2
  • 4