轻松愉快地开始使用 Rmarkdown
Dec 23, 2017
2 minute read

R 语言世界里的一个大杀器。

我想,在所有接触和学习 R 语言的初学者(当然包括我)眼里,有两个东西是相当酷的。一个是 shiny,可以轻松做出交互式的图表;而另一个就是 Rmarkdown 了。

现如今我想 markdown 是何物已经不用过多介绍了,它语法简洁,门槛很低,已经到了一种是个人就会的地步。那 Rmarkdown 到底是什么呢?

Rmarkdown 的官网上有这样几段介绍:

Turn your analyses into high quality documents, reports, presentations and dashboards. Use a productive notebook interface to weave together narrative text and code to produce elegantly formatted output. Use multiple languages including R, Python, and SQL.

简单来说,就是 Rmarkdown 能够使用 markdown 的语法,支持多种语言代码的运行和输出(R, Python 和 SQL),输出高质量的文档。

这个所谓的「高质量」的文档到底是怎么样的呢?可以这么说,有不少的人都认为 Rmarkdown 可以成为科技写作的主流:

既然说了这么多,我们就来简单看一看 Rmarkdown 的真正表现。我会将 markdown 里使用的大多数常用语法在 Rmarkdown 里展示出来。

新建一个 Rmarkdown 文件

我使用的是 Rstudio,可以在 File >> New File >> R Markdown... 里新建一个 Rmarkdown 文档。

新建 Rmarkdown

填入文档标题和作者名即可,下面的可以选择默认选项(在后来可以轻松改变)。

如何使 Rmarkdown 完美支持中文

  1. 我的环境是 Mac OSX 系统,安装 MacTex
  2. 在 RStudio 的 Preferences 中的 「Sweave」 里把 「Weave Rnw files using」改为 「knitr」,「Type LaTeX into PDF using」 改为 「XeLaTeX」
  3. 在 Rmarkdown 文档的同路径下创建一个 header.tex,内容是\usepackage{ctex},然后把 Rmarkdown 文档 yaml 栏内的内容改为如下:
title: "我的第一个 Rmarkdown 文档"
author: "anthor"
output:
  pdf_document:
    includes:
      in_header: header.tex
    keep_tex: yes
    latex_engine: xelatex
  html_document: default

测试一下:

中文显示
测试中文的显示效果。
这里先输入一段文字,我们这段文字的目的是测试在 Rmarkdown 中中文的显示效果:
* 列表项目 1
* 列表项目 2
* 列表项目 3

输出的 pdf 显示为: 中文输出

完美!

加粗,链接和行内代码块

一段常见的 Markdown 语法:

## Start with a cool section

You can use traditional **Markdown** syntax, such as [links](http://yihui.name/knitr) and `code`. Here is a quote:

> A girl phoned me the other day and said "Come on over, there's nobody home." I went over. Nobody was home. -- Rodney Dangerfield

显示为: 显示一

运行 R 代码

写入一段 R 语言代码,会在编译时自动运行: code

在 pdf 中显示为: codepdf

还可以使用 R 语言强大的画图功能: plot

在 pdf 中显示为: plotpdf

数学公式

Rmarkdown 中同样完美支持数学公式的书写:

## A little bit math

Our regression equation is $Y=`r b[1]` + `r b[2]`x$, and the model is:

$$ Y = \beta_0 + \beta_1 x + \epsilon$$

显示为: equation

表格

使用 Markdown 提供的表格语法:

Table: Demonstration of simple table syntax.

Right Left Center  Default
----- ---- ------  -------
   12 12     12        12  
  123 123   123       123
    1 1      1          1

我们得到的是我们希望的三线图格式: table

其他的比如脚注,有序列表,无序列表,定义等等不再做过多展示,上面提到的内容已经足以证明 Rmarkdown 的强大。而这些东西的学习成本几乎为零,这太令人不可思议了。