R Markdown 语法新手指南
Markdown
![](/data/attachment/album/202303/15/090943m64sk4k496l4f99q.jpg)


你可能已经了解过轻量级标记语言 Markdown。如果你是第一次接触这个概念，请参考我们的 [Markdown 指南](https://itsfoss.com/markdown-guide/)。概括来讲，它是一种用于创建纯文本文档的简单又高效的语言。


然而，Markdown 在制作详细的报告或技术文件方面可能还不够完善。


受益于 [knitr](https://www.r-project.org/nosvn/pandoc/knitr.html) 和 Pandoc 等软件包，**交互式文件格式 R Markdown** 早在 2014 年就出现了。它将纯文本与内嵌的 R 代码相结合，可以制作动态文件。


你可以使用 [各种 IDE](https://itsfoss.com/best-modern-open-source-code-editors-for-linux/) 和扩展来创建 R Markdown 文档，官方 IDE 为 **RStudio**。因此，在这篇文章中，我们将重点介绍**使用 RStudio 学习 R Markdown 语法**。



> 
> ?（假如你没有了解过，）**R 编程语言** 是一种用于统计计算、图形表示和报告的语言。
> 
> 
> 


### 配置 RStudio


通过合适的配置，你可以很轻松地用 RStudio 来编写 R Markdown。只需要安装一个软件包，就已经完成了大部分的工作！


安装 RStudio 后，在 “<ruby> 工具 <rt>  Tools </rt></ruby>” 菜单中选择 “<ruby> 安装软件包 <rt>  Install Packages </rt></ruby>” 选项。


![在 RStudio 的工具菜单下选择安装软件包选项](/data/attachment/album/202303/15/090952z7tj0f79vh7ixv8t.png)


在弹出的对话框中，搜索 “rmarkdown” 并安装。


![通过搜索并在新的软件包安装对话框中按下安装按钮来安装 Rmarkdown 软件包](/data/attachment/album/202303/15/090953kjpgmava9cvmztmy.png)



> 
> ? 如果你想使用类似 Python 的代码块，你需要安装额外的包。当你想在你的文档中包含这些包时，RStudio 会提示你安装所需的包。
> 
> 
> 


安装完成后，你可以通过选择 “<ruby> 文件 <rt>  File </rt></ruby> > <ruby> 新建文件 <rt>  New File </rt></ruby> > R Markdown” 来新建一个 R Markdown 文档。


![从文件菜单中创建一个新的 RMarkdown 文档](/data/attachment/album/202303/15/090953kh2kkw4xhxff6228.png)


之后会提示你添加一些关于文件的信息（文件的元数据），把这些填上就可以了。


![用 R Markdown 语法写出标题和其他细节](/data/attachment/album/202303/15/090954qg449fg7my04frtm.png)


或者你可以创建一个空的文件从零开始。


### RMarkdown 语法


由于它是 “加强版的 Markdown”，因此大多数语法与 Markdown 是一样的。


它还有一些 Markdown 支持不完善的东西，比如**表格、数学方程式、代码块等等**。


下面是我们要介绍的内容的概括：




| RMarkdown 块名 | 语法 |
| --- | --- |
| 标题 | `# 一级标题``## 二级标题``### 三级标题``一级标题``=======``二级标题``-------` |
| 着重 | `*斜体*``_斜体_``**加粗**``__加粗__` |
| 列表 | 无序列表：`* 列表项``* 列表项``+ 子项``+ 子项`有序列表：`1. 列表项``2. 列表项``+ 子项``+ 子项` |
| 代码块 | 普通代码块：``````这里写代码``````R 代码块：````{r}``R 代码``````你也可以用其他的语言`行内 `代码`` |
| 链接 | 普通链接：粘贴 URL带标题的链接：`[显示的文本](URL_地址)`跳转到锚点： `[显示的文本](#锚点)` |
| 表格 | `| 列名 | 列名 | 列名 |``| ------ | ------ | ------ |``| 项内容 | 项内容 | 项内容 |``| 项内容 | 项内容 | 项内容 |` |
| 方程式 | 行内方程式 `$Equations$`展示方程式： `$$Equations$$` |
| 图片 | 无标题： `![](图片链接)`有标题：`![可选标题](图片地址)` |
| 引用块 | `> 输入你引用的内容` |
| 其他 | 上角标：`文本内容^上角标^`章或页水平分割线`=========` 或 `----------`行尾输入两个以上空格，即可添加人工行分割 |


#### YAML 头


在一个 R Markdown 文档的顶部，有一个 YAML 头，被两行 `---` 包围。这个块定义了文档的最终样式，通常包含一个标题、作者、日期和你想输出的文件类型。


支持的文件格式有三种：**HTML、PDF 和 Word**。



```
---
title: "Sample"
author: "It's FOSS"
date: "2023-02-08"
output: pdf_document
---

```

这可以在 RStudio 中设置新文件时添加，如上节所示。


#### 标题


在 R Markdown 中，有两种方法指定标题。我们可以使用 `#` 字符来表示不同级别的标题，比如:



```
# Heading Level 1
## Heading Level 2
### Heading Level 3
#### Heading Level 4
##### Heading Level 5
###### Heading Level 6

```

也可以用 `=` 和 `-` 分别表示一级和二级标题。



```
一级标题
===============

二级标题
---------------

```

![rmarkdown 文件中不同等级的标题](/data/attachment/album/202303/15/090954u3ahho6m2e3onzgg.png)


#### 列表


有两种列表，一种是**无序列表**，用点句符来表示：



```
* Item 1
* Item 2
		+ Sub 1
		+ Sub 2
* Item 3

```

另一种是**有序列表**，用数字来排序：



```
1. Item 1
2. Item 2
		+ Sub 1
		+ Sub 2
3. Item 3

```

![有序和无序列表示例](/data/attachment/album/202303/15/090955epecu420wfu46j4c.png)


#### 段落中的文本格式


格式化文本有几种方式。


![](/data/attachment/album/202303/15/090955d57077xgkhxtk7g0.png)


你可以使用斜体或加粗来着重表示文本：


* 斜体：在文本前后各输入一个星号或下划线
* 加粗：在文本前后各输入两个星号或下划线



```
*这里是斜体内容*
_这里是斜体内容_

**这里是加粗内容**
__这里是加粗内容__

```


> 
> ? 你可以阅读我们的文章 [Markdown 中怎么让内容变成加粗和斜体](https://itsfoss.com/markdown-bold-italic/) 来了解更多内容。
> 
> 
> 


如果你想使用上角标，在想变成上角标的内容前后加上 `^` 符号。



```
普通文本内容^上角标^

```

如果你想对文本内容加删除线，在文本前后加 `~~` 符号。



```
~~被删除的内容~~

```

![](/data/attachment/album/202303/15/090955gpu9p38pzd0pscp0.png)


#### 添加代码块


内嵌代码是 R Markdown 最主要的设计目的。我们有几种添加代码的方式。


##### 添加普通代码块


如果你想添加一个代码块来与其他的文本进行区分，可以使用下面的语法：



```
```
这里输入你的代码
```

```

你也可以尝试 [对添加的代码进行高亮显示](https://itsfoss.com/markdown-code-block/)。


如果你想添加代码并将其输出嵌入到文档中，你可以在后面加上语言，并用大括号包裹：



```
```{语言}
这里输入你的代码
```

```

你可以用 ``` 符号来添加行内代码。



```
这里是 `行内代码`

```

它看起来是这样的：


![](/data/attachment/album/202303/15/090956jv88tnbvvv8rblv1.png)


#### 链接


如果想添加普通文本链接，把它粘贴到行内就可以了。



```
https://itsfoss.com

```

添加超链接，使用下面的语法：



```
[文本内容](URL 地址)

```

当你想链接到本页内的某个锚点时，使用下面的语法：



```
[文本内容](#锚点名称)

```

![](/data/attachment/album/202303/15/090957haotprypzbp1sgyo.png)


#### 表格


表格的语法与 Markdown 相似：



```
| 列表 | 列表 | 列表 |
| --- | --- | --- |
|表格项|表格项|表格项|
|表格项|表格项|表格项|

```

![](/data/attachment/album/202303/15/090958rna9nnv94m6q9asl.png)



> 
> ? 还想了解更多？请阅读我们的 [用 Markdown 创建表格](https://itsfoss.com/markdown-table/) 指南。
> 
> 
> 


#### 图片


添加图片使用下面的语法：



```
![](http://example.com/logo.png)

```

或



```
![可选显示文本](figures/img.png)

```

![](/data/attachment/album/202303/15/090958v5537nh2vp3yj03y.png)


#### 块引用


RMarkdown 可以添加块引用。在被引用的行或段落前添加 `>`（大于号）。



```
这里是普通文本内容。

> 这里是块引用

```

![](/data/attachment/album/202303/15/090959term5fsg2655qfam.png)



> 
> ? 如果你想了解更多块引用的内容，请阅读我们的 [Markdown 引用](https://itsfoss.com/markdown-quotes/) 指南。
> 
> 
> 


#### 方程式


你可以用 RMarkdown 来添加方程式和展示复杂的 LaTex 方程式。


例如：



```
行内方程式：$Equation$

展示方程式：$$Equation$$

```

![在 R Markdown 文档中添加方程式](/data/attachment/album/202303/15/090959riq6f6kiqkgzh19s.png)


#### 章或页水平分割线


使用三个以上星号或减号来添加章或页水平分割线。



```
************

------------

```

你可以在行尾添加两个以上的空格来添加人工行分割。


### R Markdown 非常有用（备忘录）


![](/data/attachment/album/202303/15/091233m62g6c6n763elx27.jpg)



> 
> **[R Markdown 备忘录.pdf 下载文档](https://itsfoss.com/content/files/2023/02/R-Markdown-Cheat-Sheet.pdf)**
> 
> 
> 


*? 你还知道其他关于 R Markdown 的内容吗？请在下面的评论区告诉我们。*




---


via: <https://itsfoss.com/r-markdown/>


作者：[Sreenath](https://itsfoss.com/author/sreenath/) 选题：[lkxed](https://github.com/lkxed/) 译者：[lxbwolf](https://github.com/lxbwolf) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
![Warp Terminal](/assets/images/warp-terminal.webp)


![Warp Terminal](/assets/images/warp-terminal.webp)

You probably already know about the lightweight Markdown markup language. Refer to our [Markdown guide](https://itsfoss.com/markdown-guide/), if you're new to the concept. Overall, it is a simple and effective language for creating plain-text documents.

However, Markdown may not be enough to make detailed reports or technical documents.

Hence, **R Markdown** as an **interactive file format** came into existence back in 2014 thanks to packages like [knitr](https://www.r-project.org/nosvn/pandoc/knitr.html) and [Pandoc]( knitr, and Pandoc). It combines plain text with in-line R code, helping you make a dynamic document.

To create R Markdown documents, you can use [various IDEs](https://itsfoss.com/best-modern-open-source-code-editors-for-linux/) and extensions to make it possible. However, the official IDE that helps you do it is **RStudio**. So, in this article, we will focus on **learning R Markdown syntax using RStudio**.

**R programming language**is used for statistical computing, graphics representation, and reporting.

**Suggested Read 📖**

[How to Install and Use R on UbuntuBrief: This tutorial teaches you to install R on Ubuntu. You’ll also learn how to run your first R program in Ubuntu using various methods. R, together with Python, is the most commonly used programming language for statistical computing and graphics, making it easy to work with data. With](https://itsfoss.com/install-r-ubuntu/)![](https://itsfoss.com/content/images/wordpress/2019/06/install-r-on-ubuntu.jpg)


![](https://itsfoss.com/content/images/wordpress/2019/06/install-r-on-ubuntu.jpg)

## Setting RStudio

RStudio makes it easy to work with R Markdown by its setup process. You just need to install a package, and you are done for the most part!

Once you have RStudio installed, head to the Tools menu and select the *Install Packages* option.

![Select Install Packages option under Tools menu in RStudio](https://itsfoss.com/content/images/2023/02/select-install-packages.png)

*Select Install Packages option under Tools menu (click to enlarge image)*

On the new dialog box, search for rmarkdown and install it.

![Install RMarkdown Package by searching it and pressing install button on the new package install dialog box](https://itsfoss.com/content/images/2023/02/install-rmarkdown-1.png)

*Install RMarkdown Package (click to enlarge image)*

Once installed, you can start a new rmarkdown document by selecting **File > New > RMarkdown**.

![Create a new RMarkdown Document from File menu](https://itsfoss.com/content/images/2023/02/new-r-markdown.png)

*Create a new RMarkdown Document (click to enlarge image)*

This will prompt you to add some information regarding the document (metadata for the file). Fill those up.

![Provide the title and other details for new document in rmarkdown](https://itsfoss.com/content/images/2023/02/new-document-in-rmark.png)

*New document in rmarkdown (click to enlarge image)*

Or you can create an empty document to start fresh.

## RMarkdown Syntax

Since it is just "**enhanced Markdown**," most syntax remains the same.

There would be some differences when you add things not usually supported with Markdown, like **tables, math equations, code chunks, etc.**

Here's a quick summary of what we will be covering:

Name of the RMarkdown Block | Proper Syntax |
---|---|

Heading | # Level 1 ## Level 2 ### Level 3 Level 1 ======= Level 2 ------- |

Emphasis | *Italics* _Italics_ **Bold** __Bold__ |

List | Unordered List * Item * Item + Sub + Sub Ordered List 1. Item 2. Item + Sub + Sub |

Code Chunk | Normal Code Block ``` Code Goes Here ``` R Code Block ```{r} R CODE ``` You can use other languages also. Inline `code` |

Links | Plain Link: Paste the URL Link with Caption: [Text](URL_Address) Link to a section: [Text](#Name-of-section) |

Table | | Column | Column | Column | | ------ | ------ | ------ | | Item | Item | Item | | Item | Item | Item | |

Equations | In line Equations: $Equations$ Display Equations: $$Equations$$ |

Images | Without Caption: ![](Link-to-Image) With Caption : ![optional caption text](Location-of-image) |

Block Quotes | > Type your Block Quotes |

Misc | Super Script : Text^Superscript^ Horizontal rule or Page Break: ========= or ---------- For Manual Line break, end line with 2+ spaces |


### The YAML Header

At the top of a Rmarkdown document, there is a YAML header enclosed within two `---`

. This block usually contains a title, author, date, and the file type you want to output, defining the **final look of the document.**

The file type is either **HTML, PDF, or Word.**

```
---
title: "Sample"
author: "It's FOSS"
date: "2023-02-08"
output: pdf_document
---
```


This can be added while setting the new document in RStudio, which is shown in the above section.

### Heading

In R Markdown, we can give heading in two different methods. Either we can use the # character for different levels of heading like:

```
# Heading Level 1
## Heading Level 2
### Heading Level 3
#### Heading Level 4
##### Heading Level 5
###### Heading Level 6
```


Or, `=`

and `-`

for level 1 and 2 headings, respectively.

```
Level 1 Heading
===============
Level 2 Heading
---------------
```


![various types of heading levels in rmarkdown file](https://itsfoss.com/content/images/2023/02/Headings.png)

### Lists

There are two types of Lists, the first one is an **Unordered list**, or you could call them bullet points:

```
* Item 1
* Item 2
+ Sub 1
+ Sub 2
* Item 3
```


And the second one is the **Ordered list**, which is the numbered type:

```
1. Item 1
2. Item 2
+ Sub 1
+ Sub 2
3. Item 3
```


![order and unordered list example](https://itsfoss.com/content/images/2023/02/List.png)

**Suggested Read 📖**

[Read and Organize Markdown Files in Linux Terminal With GlowGlow is a CLI tool that lets you render Markdown files in the Linux terminal. You can also organize Markdown files with it.](https://itsfoss.com/glow-cli-tool-markdown/)![](https://itsfoss.com/content/images/wordpress/2022/01/glow-cli-markdown.png)


![](https://itsfoss.com/content/images/wordpress/2022/01/glow-cli-markdown.png)

### Format text within a paragraph

There are several ways to format text.

![](https://itsfoss.com/content/images/2023/02/emphasis.png)

You can add emphasis to the text like italics or bold using:

- Italics: Place the text in between single asterisks or single underscore
- Bold: Place the text in between double asterisks or double underscores.

```
*This is Italicized text*
_This is Italicized text_
**This is Bold Text**
__This is Bold Text__
```


You can explore on this using our resource on [how to add bold and italic text in Markdown](https://itsfoss.com/markdown-bold-italic/).

If you want to add superscript to a text, place the text that should be superscript in between `^`

symbol.

`Normal Text^super_script^`


Or, if you want to add text strike-through, place the text in between two `~~`

symbol.

`~Strike Through this~~`


![](https://itsfoss.com/content/images/2023/02/superescript.png)

### Adding Code Chunks

Embedding code is the primary purpose of R Markdown. It allows us to add codes in several ways.

**Adding Normal code block.**

If you want to add a normal code block to separate it from other text, use the syntax below:

```
```
Your Code Goes Here
```
```


You can also try [adding code blocks with syntax highlighting](https://itsfoss.com/markdown-code-block/).

You should append the language in curly braces if you want to add code and embed its output to the document:

```
```{Language}
Your Code Goes Here
```
```


Or, you can add inline codes by placing the respective text between ` symbols.

` The `code` is a code`


Here's how it should look like:

![](https://itsfoss.com/content/images/2023/02/code-chunk.png)

### Links

To add a link as plain text, just paste the link as it is in a line.

`https://itsfoss.com`


Or, to make a text hyperlink, use the syntax:

`[Text](URL Address)`


Another way to add a link is, when you want to link to a section of the page. In this case, use the syntax:

`[Text](#Name-of-section)`


![](https://itsfoss.com/content/images/2023/02/links.png)

### Tables

The syntax for adding tables is similar to that of markdown.

```
|Column|Column|Column|
| --- | --- | --- |
|Item|Item|Item|
|Item|Item|Item|
```


![](https://itsfoss.com/content/images/2023/02/table.png)

[creating tables in Markdown](https://itsfoss.com/markdown-table/).

### Images

To add an image, use the syntax:

```
![](http://example.com/logo.png)
OR
![optional caption text](figures/img.png)
```


![](https://itsfoss.com/content/images/2023/02/images.png)

### Block Quotes

RMarkdown allows you to add block quotes. To use this, use the **> (greater than)** symbol in front of the line/paragraph you want to quote.

```
This is a normal text
> This is a Block Quote
```


![](https://itsfoss.com/content/images/2023/02/block-quotes.png)

If you want to explore more use cases of blockquote, head to our [Markdown quotes](https://itsfoss.com/markdown-quotes/) guide.

### Equations

Using RMarkdown, you can add either equations or display complex LaTex equations.

For example:

```
In line Pythagorean Theorem: $Equation$
Display Equation: $$Equation$$
```


![adding equations in R Markdown document](https://itsfoss.com/content/images/2023/02/equations.png)

### Horizontal Rule / Page Break

Use three or more asterisks or dashes to add a horizontal rule /page break.

```
************
------------
```


If you want to add a manual line break, end that line with two or more spaces.

## Summary

## R Markdown is Useful (Cheat Sheet)

Whether you are working with scientific reports or want to create any other type of dynamic document, R Markdown is your best bet to make the most out of Markdown.

Here's a cheat sheet to help you summarize it all:

![](https://itsfoss.com/content/images/2023/02/R-Markdown-Cheat-Sheet.webp)

*💬 Did we miss something that you use with R Markdown? Share your thoughts in the comments down below.*