Unicode with knitr and Rmarkdown

Viewed 9347

Is there a set of best practices or documentation for working with Unicode in knitr and Rmarkdown? I can't seem to get any glyphs to show up properly when knitting a document.

For example, this works in the console (in Rstudio):

> cat("\U2660   \U2665  \U2666  \U2663")
♠   ♥   ♦   ♣

But when knitting I get this:

  • HTML

enter image description here

  • Word

enter image description here

3 Answers

For anyone else who came across this after trying to get emoji support in Rstudio/Rmarkdown documents, another possible issue is that if the file encoding isn't set to UTF-8, the resulting compiled document won't support emojis either.

In order for emoji to work in Rmarkdown, you must change the file encoding of the Rmd document. Go to File -> Reopen with encoding, then select UTF-8.

Once you have ensured the file is open in UTF-8 encoding, you should be able to compile with emoji support.

You should even be able to paste emoji from a browser directly into the document.

It is probably a good idea to change the default encoding for all files to UTF-8 so that you don't have to deal with this issue again.

Unicode: Inline

Phew, that was close `r knitr::asis_output("\U1F605  \U2660   \U2665  \U2666  \U2663")` 

enter image description here

Unicode: Block

```{r, echo=FALSE} 
knitr::asis_output("Phew, that was close \U1F605  \U2660   \U2665  \U2666  \U2663")
```

enter image description here

The emo package

Unfortunately, this package isn't yet on CRAN, but it can be installed with devtools::install_github("hadley/emo")

emo::ji("face")

There are some more examples here

Related