13 min read

RMarkdown的使用技巧

本文于2020-10-10更新。 如发现问题或者有建议,欢迎提交 Issue 更多问题参考github

1 前言

1.1 新增

  • 整理的\(\LaTeX\)
  • cross reference
  • 整理的\(\LaTeX\), 2018-05-04

2 yaml option

yaml文档要修改对应路径下的文档,才能修改样式。

2.1 目录

output:
  html_document:
    toc: true
    toc_float:
      collapsed: false
      smooth_scroll: false

toc_float浮动目录,这个不需要记忆,我倾向大家在这里设置。(RStudio 2018)

2.2 df_printDT::datatable方便(RStudio 2018)

output:
  html_document:
    df_print: paged

2.3 Code Folding

  • code_folding: hide
  • code_folding: show 用户可以自己选择隐藏。(RStudio 2018)

2.4 Shared Options

建立一个_output.yaml,这样就不需要重复设置了。 与_output.yaml同一文件夹的.Rmd文件,不需要设置html_document的格式了。(RStudio 2018)

2.5 fig size

---
title: "Habits"
output:
  html_document:
    fig_width: 7
    fig_height: 6
    fig_caption: true
---

参考 Yihui Xie (2018)

3 整理的\(\LaTeX\)

Xie (2018b) 提供了Rmd中使用\(\LaTeX\)、安装相关包的解决方案。

3.1 报错部分

  • (Datta 2017, 40)给出的Quoted Texts和flushright没有执行成功。
  • (Datta 2017, 57)给出的tabbing环境没有执行成功。我估计是需要在.tex文件声明的话,可以执行,因为\hspace我之前成功使用过。

3.2 上下括号

brace 有弓形的意思。 这里使用

  • \overbrace
  • \underbrace

\[A = \overbrace{a_1 + a_2 + a_3 }^{\text{Part 1}} + \underbrace{a_4 + a_5 + a_6 }_{\text{Part 2}}\]

  • 注意一个是^一个是_

3.3 \mbox{}, \text{}, \mathrm{}比较

\(\LaTeX\)公式中,字体都是斜体,因此 \mbox{}, \text{}, \mathrm{}可以防止字体斜体。 但是\mbox{}, \text{}会让字体的数学模式消失,然而\mathrm{}不会 (Datta 2017)。 具体见例子, \mbox{A_2}, \text{A_2},\mathrm{A_3}, A_3

\[\mbox{A_2}, \text{A_2},\mathrm{A_3}, A_3\]

我们发现只有A_3是斜体,其余都是正常的。 其次,只有\mathrm{A_3}, A_3保持了下角标。 综上,我们选择\mathrm

3.4 点点点

\[\ldots, \cdots: i = 1,\ldots,n\] \ldots, \cdots: i = 1,\ldots,n,推荐使用\(\ldots\),更符合印刷体。

3.5 conditioning的书写

\[\frac{\partial f(x)}{\partial x} |_{x=0} = f^{\prime} (0)\] \frac{\partial f(x)}{\partial x} |_{x=0} = f^{\prime} (0): 这里使用|_{x=0}而非|x=0

3.6 自定义函数

\newcommand{变量名称}{变量内容}

例如, \newcommand{\bs}{\backslash}表示用\bs表示\backslash

比如

\(\backslash: 这是一个自定义的函数\)

3.7 to-do

\surd: \(\surd\) (Datta 2017, 253)

3.8 等号对齐

\[\begin{alignat}{2} 1 + 1 & = 2\\ 1 + 10 & = 11\\ \end{alignat}\]

3.9 mathbb

\(\LaTeX\)中是使用\mathbb{}函数实现的有

  1. indicator function \(\mathbb{I}\)
  2. 实数集合 \(\mathbb{R}\) (Wikibooks 2014)

3.10 箭头 Arrow

参考 Frank (2012) 箭头相关的\(\LaTex\)代码。

library(rvest)
xml <- read_html('http://www.sascha-frank.com/Arrow/latex-arrows.html')
library(glue)
xml %>% 
    html_nodes('td') %>% 
    html_text() %>% 
    str_subset('\\\\[A-z]{1,}') %>% 
    paste0('+ \`',.,'\`',': $',.,'$') %>% 
    # str_replace_all('\\$','$') %>% 
    # 这一步还是需要手动去剔除,不能用正则化
    paste(collapse = '\n') %>% 
    write_file('latex.txt')

参考 Xie (2018b) 安装相应地 \(\LaTex\) 包。

library(tinytex)
tlmgr_search('/stmaryrd.sty')
tlmgr_install('stmaryrd')
tlmgr_update()  

tlmgr_search('/MnSymbol.sty')
tlmgr_install('MnSymbol')
  • \uparrow: \(\uparrow\)
  • \downarrow: \(\downarrow\)
  • \Uparrow: \(\Uparrow\)
  • \Downarrow: \(\Downarrow\)
  • \updownarrow: \(\updownarrow\)
  • \Updownarrow: \(\Updownarrow\)
  • \leftarrow: \(\leftarrow\)
  • \rightarrow: \(\rightarrow\)
  • \leftrightarrow: \(\leftrightarrow\)
  • \Leftrightarrow: \(\Leftrightarrow\)
  • \Leftarrow: \(\Leftarrow\)
  • \Rightarrow: \(\Rightarrow\)
  • \longleftarrow: \(\longleftarrow\)
  • \longrightarrow: \(\longrightarrow\)
  • \Longleftarrow: \(\Longleftarrow\)
  • \Longrightarrow: \(\Longrightarrow\)
  • \longleftrightarrow: \(\longleftrightarrow\)
  • \Longleftrightarrow: \(\Longleftrightarrow\)
  • \nwarrow: \(\nwarrow\)
  • \nearrow: \(\nearrow\)
  • \swarrow: \(\swarrow\)
  • \searrow: \(\searrow\)
  • \mapsto: \(\mapsto\)
  • \longmapsto: \(\longmapsto\)
  • \hookleftarrow: \(\hookleftarrow\)
  • \hookrightarrow: \(\hookrightarrow\)
  • \leftharpoonup: \(\leftharpoonup\)
  • \rightharpoonup: \(\rightharpoonup\)
  • \leftharpoondown: \(\leftharpoondown\)
  • \rightharpoondown: \(\rightharpoondown\)
  • \rightleftharpoons: \(\rightleftharpoons\)
  • \twoheadleftarrow: \(\twoheadleftarrow\)
  • \twoheadrightarrow: \(\twoheadrightarrow\)
  • \Lsh: \(\Lsh\)
  • \Rsh: \(\Rsh\)
  • \leftleftarrows: \(\leftleftarrows\)
  • \rightrightarrows: \(\rightrightarrows\)
  • \upuparrows: \(\upuparrows\)
  • \downdownarrows: \(\downdownarrows\)
  • \rightleftarrows: \(\rightleftarrows\)
  • \leftrightarrows: \(\leftrightarrows\)
  • \Lleftarrow: \(\Lleftarrow\)
  • \Rrightarrow: \(\Rrightarrow\)
  • \leftarrowtail: \(\leftarrowtail\)
  • \rightarrowtail: \(\rightarrowtail\)
  • \rightsquigarrow: \(\rightsquigarrow\)
  • \leftrightsquigarrow: \(\leftrightsquigarrow\)
  • \looparrowleft: \(\looparrowleft\)
  • \looparrowright: \(\looparrowright\)
  • \circlearrowleft: \(\circlearrowleft\)
  • \circlearrowright: \(\circlearrowright\)
  • \curvearrowleft: \(\curvearrowleft\)
  • \curvearrowright: \(\curvearrowright\)
  • \upharpoonleft: \(\upharpoonleft\)
  • \upharpoonright: \(\upharpoonright\)
  • \downharpoonleft: \(\downharpoonleft\)
  • \downharpoonright: \(\downharpoonright\)
  • \nleftarrow: \(\nleftarrow\)
  • \nrightarrow: \(\nrightarrow\)
  • \nLeftarrow: \(\nLeftarrow\)
  • \nRightarrow: \(\nRightarrow\)
  • \nleftrightarrow: \(\nleftrightarrow\)
  • \nLeftrightarrow: \(\nLeftrightarrow\)
  • \overleftarrow{Text}: \(\overleftarrow{Text}\)
  • \overrightarrow{Text}: \(\overrightarrow{Text}\)
  • \underleftarrow{Text}: \(\underleftarrow{Text}\)
  • \underrightarrow{Text}: \(\underrightarrow{Text}\)
  • \overleftrightarrow{Text}: \(\overleftrightarrow{Text}\)
  • \underleftrightarrow{Text}: \(\underleftrightarrow{Text}\)
  • A \xLongleftarrow[\text{unten Text}]{\text{oben Text}} B: $A B $
  • A \xLongleftarrow{\text{ganz langer text}} B: $A B $
  • A \xLongrightarrow[\text{unten Text}]{\text{oben Text}} B: \(A \xLongrightarrow[\text{unten Text}]{\text{oben Text}} B\)
  • A \xLongrightarrow{\text{ganz langer text}} B: $ A B$
  • A \xLongleftrightarrow[\text{unten Text}]{\text{oben Text}} B: \(A \xLongleftrightarrow[\text{unten Text}]{\text{oben Text}} B\)
  • A \xLongleftrightarrow{\text{ganz langer text}} B: \(A \xLongleftrightarrow{\text{ganz langer text}} B\)
  • A \xLeftrightarrow[\text{unten Text}]{\text{oben Text}} B: \(A \xLeftrightarrow[\text{unten Text}]{\text{oben Text}} B\)
  • A \xLeftrightarrow{\text{ganz langer text}} B: \(A \xLeftrightarrow{\text{ganz langer text}} B\)
  • A \xlongleftrightarrow[\text{unten Text}]{\text{oben Text}} B: \(A \xlongleftrightarrow[\text{unten Text}]{\text{oben Text}} B\)
  • A \xlongleftrightarrow{\text{ganz langer text}} B: \(A \xlongleftrightarrow{\text{ganz langer text}} B\)
  • A \xlongrightarrow[\text{unten Text}]{\text{oben Text}} B: \(A \xlongrightarrow[\text{unten Text}]{\text{oben Text}} B\)
  • A \xlongrightarrow{\text{ganz langer text}} B: \(A \xlongrightarrow{\text{ganz langer text}} B\)
  • A \xlongrightarrow{} B: \(A \xlongrightarrow{} B\)
  • A \xleftrightarrow[\text{unten Text}]{\text{oben Text}} B: \(A \xleftrightarrow[\text{unten Text}]{\text{oben Text}} B\)
  • A \xleftrightarrow{\text{ganz langer text}} B: \(A \xleftrightarrow{\text{ganz langer text}} B\)
  • A \xlongleftarrow[\text{unten Text}]{\text{oben Text}} B: \(A \xlongleftarrow[\text{unten Text}]{\text{oben Text}} B\)
  • A \xlongleftarrow{\text{ganz langer text}} B: \(A \xlongleftarrow{\text{ganz langer text}} B\)
  • A \xlongleftarrow{} B: \(A \xlongleftarrow{} B\)
  • A \xleftarrow[\text{unten Text}]{\text{oben Text}} B: \(A \xleftarrow[\text{unten Text}]{\text{oben Text}} B\)
  • A \xleftarrow{\text{ganz langer text}} B: \(A \xleftarrow{\text{ganz langer text}} B\)
  • A \xrightarrow[\text{unten Text}]{\text{oben Text}} B: \(A \xrightarrow[\text{unten Text}]{\text{oben Text}} B\)
  • A \xrightarrow{\text{ganz langer text}} B: \(A \xrightarrow{\text{ganz langer text}} B\)
  • A \xlongequal[\text{unten Text}]{\text{oben Text}} B: $A B $
  • A \xlongequal{\text{ganz langer text}} B: $A B $
  • \Rsh: \(\Rsh\)
  • \Lsh: \(\Lsh\)
  • \Rsh: \(\Rsh\)
  • \rotatebox[origin=c]{90}{$\Rsh$}: \(\rotatebox[origin=c]{90}{\)\(}\)
  • \rotatebox[origin=c]{180}{$\Rsh$}: \(\rotatebox[origin=c]{180}{\)\(}\)
  • \rotatebox[origin=c]{270}{$\Rsh$}: \(\rotatebox[origin=c]{270}{\)\(}\)
  • \Lsh: \(\Lsh\)
  • \rotatebox[origin=c]{90}{$\Lsh$}: \(\rotatebox[origin=c]{90}{\)\(}\)
  • \rotatebox[origin=c]{180}{$\Lsh$}: \(\rotatebox[origin=c]{180}{\)\(}\)
  • \rotatebox[origin=c]{270}{$\Lsh$}: \(\rotatebox[origin=c]{270}{\)\(}\)
  • \rightarrow oder \to: \(\rightarrow oder \to\)
  • \Rightarrow: \(\Rightarrow\)
  • \longrightarrow: \(\longrightarrow\)
  • \Longrightarrow: \(\Longrightarrow\)
  • \mapsto: \(\mapsto\)
  • \longmapsto: \(\longmapsto\)
  • \hookrightarrow: \(\hookrightarrow\)
  • \rightharpoonup: \(\rightharpoonup\)
  • \rightharpoondown: \(\rightharpoondown\)
  • \twoheadrightarrow: \(\twoheadrightarrow\)
  • \Rsh: \(\Rsh\)
  • \rightrightarrows: \(\rightrightarrows\)
  • \Rrightarrow: \(\Rrightarrow\)
  • \rightarrowtail: \(\rightarrowtail\)
  • \rightsquigarrow: \(\rightsquigarrow\)
  • \looparrowright: \(\looparrowright\)
  • \circlearrowright: \(\circlearrowright\)
  • \curvearrowright: \(\curvearrowright\)
  • \nrightarrow: \(\nrightarrow\)
  • \nRightarrow: \(\nRightarrow\)
  • \rhookrightarrow: \(\rhookrightarrow\)
  • \dashedrightarrow: \(\dashedrightarrow\)
  • \leadsto: \(\leadsto\)
  • \rcurvearrowright: \(\rcurvearrowright\)
  • \rcirclearrowright: \(\rcirclearrowright\)
  • \lcirclearrowright: \(\lcirclearrowright\)
  • \nhookrightarrow: \(\nhookrightarrow\)
  • \nrhookrightarrow: \(\nrhookrightarrow\)
  • \nrightharpoonup: \(\nrightharpoonup\)
  • \nrightharpoondown: \(\nrightharpoondown\)
  • \ndashedrightarrow: \(\ndashedrightarrow\)
  • \nrightrightarrows: \(\nrightrightarrows\)
  • \nleadsto: \(\nleadsto\)
  • \nrightrsquigarrow: \(\nrightrsquigarrow\)
  • \ncurvearrowright: \(\ncurvearrowright\)
  • \nrcurvearrowright: \(\nrcurvearrowright\)
  • \nrcirclearrowright: \(\nrcirclearrowright\)
  • \nlcirclearrowright: \(\nlcirclearrowright\)
  • \ncirclearrowright: \(\ncirclearrowright\)
  • \nmapsto: \(\nmapsto\)
  • \nRrightarrow: \(\nRrightarrow\)
  • \leftarrow bzw. \gets: $bzw. $
  • \Leftarrow: \(\Leftarrow\)
  • \longleftarrow: \(\longleftarrow\)
  • \Longleftarrow: \(\Longleftarrow\)
  • \hookleftarrow: \(\hookleftarrow\)
  • \leftharpoonup: \(\leftharpoonup\)
  • \leftharpoondown: \(\leftharpoondown\)
  • \twoheadleftarrow: \(\twoheadleftarrow\)
  • \Lsh: \(\Lsh\)
  • \leftleftarrows: \(\leftleftarrows\)
  • \Lleftarrow: \(\Lleftarrow\)
  • \leftarrowtail: \(\leftarrowtail\)
  • \looparrowleft: \(\looparrowleft\)
  • \circlearrowleft: \(\circlearrowleft\)
  • \curvearrowleft: \(\curvearrowleft\)
  • \nleftarrow: \(\nleftarrow\)
  • \nLeftarrow: \(\nLeftarrow\)
  • \leftmapsto: \(\leftmapsto\)
  • \lhookleftarrow: \(\lhookleftarrow\)
  • \dashedleftarrow: \(\dashedleftarrow\)
  • \leftlsquigarrow: \(\leftlsquigarrow\)
  • \nleftmapsto: \(\nleftmapsto\)
  • \lcurvearrowleftt: \(\lcurvearrowleftt\)
  • \rcirclearrowleft: \(\rcirclearrowleft\)
  • \lcirclearrowleft: \(\lcirclearrowleft\)
  • \ntwoheadleftarrow: \(\ntwoheadleftarrow\)
  • \nleftarrowtail: \(\nleftarrowtail\)
  • \nhookleftarrow: \(\nhookleftarrow\)
  • \nlhookleftarrow: \(\nlhookleftarrow\)
  • \nleftharpoonup: \(\nleftharpoonup\)
  • \nleftharpoondown: \(\nleftharpoondown\)
  • \ndashedleftarrow: \(\ndashedleftarrow\)
  • \nleftleftarrows: \(\nleftleftarrows\)
  • \nleftlsquigarrow: \(\nleftlsquigarrow\)
  • \nleftrsquigarrow: \(\nleftrsquigarrow\)
  • \ncurvearrowleft: \(\ncurvearrowleft\)
  • \nlcurvearrowleft: \(\nlcurvearrowleft\)
  • \nrcirclearrowleft: \(\nrcirclearrowleft\)
  • \nlcirclearrowleft: \(\nlcirclearrowleft\)
  • \ncirclearrowleft: \(\ncirclearrowleft\)
  • \nLleftarrow: \(\nLleftarrow\)
  • \xtwoheadrightarrow[\text{oben}]{\text{unten}}: \(\xtwoheadrightarrow[\text{oben}]{\text{unten}}\)
  • \xtwoheadleftarrow[\text{oben}]{\text{unten}}: \(\xtwoheadleftarrow[\text{oben}]{\text{unten}}\)
  • \xmapsto[\text{oben}]{\text{unten}}: \(\xmapsto[\text{oben}]{\text{unten}}\)
  • \xlongequal[\text{oben}]{\text{unten}}: \(\xlongequal[\text{oben}]{\text{unten}}\)
  • \xtofrom[\text{oben}]{\text{unten}}: \(\xtofrom[\text{oben}]{\text{unten}}\)

3.11 其他

  • \(\hat{oo}, \widehat{oo}\)可能可以消除帽子错位的问题
  • \(\vec{o}\)表示向量
  • \(\dot{o} = \Delta o\)
  • \(a \hspace{20pt} b\): a \hspace{20pt} b。中间必须要指定大小。
  • \(\epsilon, \varepsilon\): \epsilon, \varepsilon。明显后面是用来记录回归中的误差项的。
  • 其他误差项表示\(\mu, \nu\): \mu, \nu
  • \because: \(\because\)
  • \therefore: \(\therefore\)
  • \(\text{补集: } \complement_UA\)
  • \(\text{交集: } \bigcap\)
  • \(\text{并集: } \bigcup\)
  • 输入:$${\forall}$$,会显示出\({\forall}\)任意符号
  • 输入:$${\exists}$$,会显示出\({\exists}\)存在符号
  • \text{abc abc} 用于写文字,里面的空格不需要插入\space(Hughes 2012)
  • 关键是\begin\end加上{alignat},其中的&\\类似于矩阵的书写方式。
  • \(\mathrm{d}x\),$\mathrm{d}x$, 导数 (CSDN 2017)
  • \(\mathbb{I}\),$\mathbb{I}$, 指示函数 (CSDN 2017)
  • \(\int\),$\int$, 积分 (CSDN 2017)
  • \(\iint\), \(\iint\), 积分 (CSDN 2017)
  • \(\iint\), \(\iint\), 积分 (CSDN 2017)
  • \(\sqrt[p]{a}\), $\sqrt[p]{a}$,n次根 (Stack Exchange 2012)
  • \(\LaTeX\) logo 输出方式 $\LaTeX$
  • overset可以在\(\LaTeX\)元素上加文字,如$\overset{A}{B}$\(\to \overset{A}{B}\)

\[\begin{alignat}{2} f(x) & = (m+n)^2 \\ & = m^2+2mn+n^2 \\ \end{alignat}\]

\begin{alignat}{2}
f(x) & = (m+n)^2 \\
& = m^2+2mn+n^2 \\
\end{alignat}

一个比较好的参考博客。

3.11.1 bold, italitic (Datta 2017, 10)

  • \textbf{}: \(\textbf{textbf}\)
  • \bf{}: \(\bf{bf}\)
  • \textit{}: \(\textit{textit}\),但是也就文本化了,下角标和上角标失效。
  • \it{}: \(\it{it}\),但是也就文本化了,下角标和上角标失效。

3.11.2 not perp (Loretan 2011)

\[\not \perp\] \[\not\perp\]

两个都行,只是在电脑上的显示是不行的,格式问题。

无限大 \(\infty\)

4 其他 Pandoc 使用技巧

4.1 举例说明(MacFarlane 2018)

(@eg1)  例子一,例子一,例子一,例子一。
(@eg2)  例子二,例子二,例子二,例子二。

正如例子(@eg1)所说,例子一,例子一,例子一,例子一。
正如例子(@eg2)所说,例子二,例子二,例子二,例子二。
  1. 例子一,例子一,例子一,例子一。
  2. 例子二,例子二,例子二,例子二。

正如例子(1)所说,例子一,例子一,例子一,例子一。 正如例子(2)所说,例子二,例子二,例子二,例子二。

4.2 脚注(MacFarlane 2018)

这里会产生一个脚注[^脚注]1,你可以点击[^脚注]上方的数字查看。

[^脚注]:
这是脚注的第一行。

    缩进两格子这一行会跟着脚注的第一行。
    
        a + b = a + b # 缩进4格,这里产生一行代码

这行没有缩进,所以不会算在脚注里,而是承接上文。

4.3 >空行问题

>引用时,

> 我  
你

后面加上一个tab就可以实现两行。


4.4 引用>的深入

多个>,但是只空一行,也是可以整体引用的。

4.5 引用空行问题

引用文段,

>xxx
xxx
xxx

最后会变成

xxx xxx xxx

使用\t

>xxx\t
xxx\t
xxx

最后会变成

xxx
xxx
xxx

替换的快捷方式
\n \(\to\) \t\n

5 PowerPoint 书写

Xie (2018a), Yihui Xie (2018) 发布了新版本的RMarkdown支持导出PowerPoint,而且交互很好,类似于其他RMarkdown导出方式,以下为测评。

安装最新的测试版本RStudio

5.1 yaml options

---
title: "Habits"
author: John Doe
date: March 22, 2005
output:
  powerpoint_presentation:
    reference_doc: corp_style.pptx
---

这里类似于docx文档书写,支持模板。

5.2 主要功能

---支持分页 code chunk支持图片命名使用fig.cap=""参数

5.3 分栏

:::::: {.columns}
::: {.column width="40%"}
Content of the left column.
:::

::: {.column width="60%"}
Content of the right column.
:::
::::::

在使用模版的时候,会乱码。

5.4 目录

toc: true

5.5 模板代码

---
title: "Habits"
author: John Doe
date: March 22, 2005
output:
  powerpoint_presentation:
    toc: true
---

# In the morning

## Getting up

- Turn off alarm
- Get out of bed

## Breakfast

- Eat eggs
- Drink coffee

# In the evening

## Dinner

- Eat spaghetti
- Drink wine

---

```r, cars, fig.cap="A scatterplot.", echo=FALSE
plot(cars)
```

## Going to sleep

- Get in bed
- Count sheep

## Multi-column layout

:::::: {.columns}
::: {.column width="40%"}
Content of the left column.
:::

::: {.column width="60%"}
Content of the right column.
:::
::::::

展示结果为 ../../../picbackup/Habits.pptx

6 html 使用技巧

6.1 details [open|close]summary建立fold功能

<details open>
<summary> Session Info </summary>  

xxxxxxxxxx
  
</details>

Session Info

xxxxxxxxxx

由于这里的参数是open,因此默认的内容是打开

<details close>
<summary> Session Info </summary>  

xxxxxxxxxx
  
</details>

Session Info

xxxxxxxxxx

由于这里的参数是close,因此默认的内容是关闭的。

并且可以对#进行fold。

<details close>
<summary> some text </summary>  

# 123

123

# 123

123

</details>

6.2 自定义的高亮方式 (Robbins 2018, 313)

<style>
.glossary {
color: #0378a9; /* blue */
background-color: red;
}
</style>

Every variety of cabbage had their origin in the wild cabbage of
Europe (<dfn class="glossary"><i>Brassica oleracea</i></dfn>)

Every variety of cabbage had their origin in the wild cabbage of Europe (Brassica oleracea)

<span style="background-color: #FFFF00">需要高亮的字</span>: 需要高亮的字

6.3 插入警告 (Robbins 2018, 322)

<style>
p.warning::before {
content: url(exclamation.png);
margin-right: 6px;
}
p.warning::after {
content: " Thank you.";
color: red;
}
</style>

`content: url(exclamation.png);` 这种需要自己去找好logo的

<p class="warning">We are required to warn you that undercooked food is
a health risk.</p>

content: url(exclamation.png); 这种需要自己去找好logo的

We are required to warn you that undercooked food is a health risk.

7 中文使用问题

7.1 captioner

\ref(...)的使用在pdf文档中,一直存在问题, captioner包是一个替代方案。

library(captioner)
## Warning: 程辑包'captioner'是用R版本3.6.3 来建造的
fig_nums <- captioner(prefix = '图',auto_space = F)
fig_nums("my_first_figure",cite = F)
## [1] "图1: "
fig_nums("my_second_figure",cite = F)
## [1] "图2: "
fig_nums("my_first_figure",cite = F)
## [1] "图1: "

会按照my_first_figuremy_second_figure来记录图片的顺序,且顺序不会乱。 教程可参考 Köhler (2018)

7.2 pdf 图片浮动

参考这篇 Stack Overflow

  1. 建立一个.tex文件,
  2. 命名为preamble-latex.tex
  3. 内容为
\usepackage{float}
\let\origfigure\figure
\let\endorigfigure\endfigure
\renewenvironment{figure}[1][2] {
  \expandafter\origfigure\expandafter[H]
} {
  \endorigfigure
}
  1. 在yaml中申明,
output:
  rmarkdown::pdf_document:
    fig_caption: yes        
    includes:  
      in_header: preamble-latex.tex

这篇 博客 的方式无效。 加入/后,标题消失了。

8 RMarkdown 使用技巧

8.1 R chunk 图片参数

{r nice-fig, fig.cap='Here is a nice figure!', out.width='80%', fig.asp=.75, fig.align='center'}

9 其他(未整理)

9.1.Rmd的文档提取出来建立.R文档

purl建立反编织。 cheatsheet,打印 可以设计是否需要文字或者不需要。

library(knitr)
purl("test.Rmd")
purl("test.Rmd", output = "test2.R", documentation = 2)

9.2 有限显示表格

cols.print=3, rows.print=3r框中设定,这个比什么head()好用多了。

9.3 一些有用的markdown

  • 1
  • 2
    • 3
    • 4
+ 1
+ 2
    + 3
    + 4

只要间隔两个tab,就可以写细分的点了。

superscript2

superscript^2^

subscript2

subscript~2~

9.4 knit style 的选择

---
output: 
  html_document: 
    theme: cosmo
---

9.5 待办事项

  • \(\boxtimes\) task 1
  • \(\square\) task 2
  • \(\Box\) task 3

available: $\boxtimes$, $\square$, $\Box$.

9.6 用excel刷批量列表

暂时不需要这项技能了,因为可以用+可以批量选择。然后用正则化替换就好。

9.7 Rmd,打出高亮的效果

Marked text <mark>Marked text</mark>

9.8 代码显示方式

\``code`框住代码,就可以实现code`,代码显示方式了。

9.9 theme选择

yaml设置中, theme: cosmo\(\to\)theme: united 可以保持英文字母不“变细”。

9.10 ## References {-}

{-}就不number headings

9.11 自动引用使用过的包

search() %>% 
  str_subset("package:") %>% 
  str_replace_all("package:","")

这个不行,因为会出现一些write_bib没有生成的引用。

write_bib(???) 基于citation函数 开发的。

write_bib(x = .packages(), file = "r_pkg.bib",prefix="")
read_csv("r_pkg.bib",col_names = FALSE) %>% 
  rename(value = X1) %>% 
  select(value) %>% 
  filter(value %in% str_subset(value,"@")) %>% 
  mutate(value = str_replace(value, "@Manual\\{","")) %>% 
  .$value %>% 
  paste("@",.,sep="",collapse = ", ") %>% 
  writeLines()

然后将其复制粘贴到正文即可。

9.12 citr使用

这个引用文献非常方便。

9.13 字体变红

<span style="color:red">需要被红的信息</span>

9.14 保留代码,不跑代码。

eval=FALSE

9.15 knitr::opts_chunk$setsetup

直接设置,不需要背诵。

## eval = F

inline 就不能写了。

9.16 bookdown::gitbook主要参数

bookdown::gitbook:
  split_by: none
  self_contained: TRUE
  df_print: paged
  • split_by: none: 建立的html文件不拆分
  • self_contained: TRUE: 生成的html文件保留样式
  • df_print: paged也是可以使用的(Martin 2017)

9.17 表格加脚注

library(knitr)
library(kableExtra)
## Warning: 程辑包'kableExtra'是用R版本3.6.3 来建造的
## 
## 载入程辑包:'kableExtra'
## The following object is masked from 'package:dplyr':
## 
##     group_rows
mtcars[1:5, 1:6] %>% 
  kable("html") %>% 
  kable_styling() %>% 
  column_spec(5:7,bold = T) %>% # 表格加粗
  row_spec(3:5, bold = T, 
           color = "white", # 字体白色
           background = "#D7261E") %>% # 背景红色
  footnote(
    footnote_as_chunk = T,
    general = "每个变量都有简单的解释。",
    general_title = "备注",
    number = c("mpg: Miles/(US) gallon",
               "cyl: Number of cylinders",
               "disp:   Displacement (cu.in.)",
               "hp: Gross horsepower",
               "drat:   Rear axle ratio",
               "wt: Weight (1000 lbs)"
               ),
    number_title = "变量解释"
  )
mpg cyl disp hp drat wt
Mazda RX4 21.0 6 160 110 3.90 2.620
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875
Datsun 710 22.8 4 108 93 3.85 2.320
Hornet 4 Drive 21.4 6 258 110 3.08 3.215
Hornet Sportabout 18.7 8 360 175 3.15 3.440
备注 每个变量都有简单的解释。
变量解释 1 mpg: Miles/(US) gallon 2 cyl: Number of cylinders 3 disp: Displacement (cu.in.) 4 hp: Gross horsepower 5 drat: Rear axle ratio 6 wt: Weight (1000 lbs)

函数footnote加脚注(Zhu 2018)

9.18 将表格存成图片

点击ExportSave as Image

9.19 选择Height = 300即可。`即可。

9.20 .bib一个都不能错

只要.bib出问题,所有都不能跑,花了1h学的教训。

9.21 get_bib函数 for rmarkdown

get_bib <- function(input,output){
  library(knitr)
  library(tidyverse)
  note_bib <- read.table(input, sep="\t") %>%
    mutate(
      pkg = str_extract(V1,"library\\([:alnum:]{2,10}\\)"),
      pkg = str_remove_all(pkg,"library\\(|\\)")
      ) %>%
    filter(!is.na(pkg)) %>%
    distinct(pkg) %>%
    .$pkg
  write_bib(note_bib,file=output,prefix = "")
  type1 <- paste("@",note_bib,sep = "",collapse = ", ")
  type2 <- paste("@",note_bib,sep = "",collapse = "; ")
  return(list(type1=type1,type2=type2))
}

"r get_bib("note.Rmd","note1.bib")$type1" 提供。

9.22 引用用分号

Here is a statement [@key1; @key2].
@key3 did something.
Some examples [e.g. @key4; @key5; but see @key6]

9.23 cross reference

  • 章节题目可以按照这个来显示,章节名称 {#haha}
  • 交叉引用格式为章节 \@ref(haha),不要以数字开头

就可以实现了。

  • blogdown 直接可以cross reference

  • html_document不可以。

  • process reading 加上cross reference。 \@ref(other) 看看。 不行

9.24 图片是webp格式

微信的图片是webp格式,不能简单插入,转化方式是通过微信打开,另存为jpeg格式,这是默认的。 目前暂时是手动的。

9.25 引用建立跳转链接 (Xie 2016, 2.8)

link-citations: true

9.26 用render实现格式修改

  • 用网页check,最简单的
library(rmarkdown)
render(file.path(dirname(getwd()),'eng_learning.Rmd'),
       word_document(
           highlight = "zenburn",
           reference_docx = "180710_word_note_sample.docx"
       ))

9.27 kable_styling使得表格更好看些

kableExtra::kable_styling函数可以让html下的表格更好看些。

9.28 kableExtra包主要函数解析

library(tidyverse)
library(knitr)
library(kableExtra)
library(formattable)
## Warning: 程辑包'formattable'是用R版本3.6.3 来建造的
mtcars[1:5, 1:6] %>%
  mutate(hp = color_bar("lightgreen")(hp)) %>%
  mutate(disp = ifelse(disp > 200
                       ,cell_spec(disp, "html", color = "red", bold = T)
                       ,cell_spec(disp, "html", color = "green", italic = T))
  ) %>%
  kable("html",escape = F) %>%
  kable_styling(full_width = F) %>%
  row_spec(3:5, bold = T,
           color = "white", # 字体白色
           background = "#D7261E") %>% # 背景红色
  footnote(
    footnote_as_chunk = T,
    general = "每个变量都有简单的解释。",
    general_title = "备注",
    number = c("mpg: Miles/(US) gallon",
               "cyl: Number of cylinders",
               "disp:   Displacement (cu.in.)",
               "hp: Gross horsepower",
               "drat:   Rear axle ratio",
               "wt: Weight (1000 lbs)"
               ),
    number_title = "变量解释"
  )
mpg cyl disp hp drat wt
21.0 6 160 110 3.90 2.620
21.0 6 160 110 3.90 2.875
22.8 4 108 93 3.85 2.320
21.4 6 258 110 3.08 3.215
18.7 8 360 175 3.15 3.440
备注 每个变量都有简单的解释。
变量解释 1 mpg: Miles/(US) gallon 2 cyl: Number of cylinders 3 disp: Displacement (cu.in.) 4 hp: Gross horsepower 5 drat: Rear axle ratio 6 wt: Weight (1000 lbs)
  • formattable::color_bar函数实现柱状图。
  • cell_spec可以改变单元格字体的颜色和形状。但是必须满足这两个要求 (朱昊 2018)
    • kable("html",escape = F) %>%
    • kable_styling(full_width = F) %>%

否则出现报错:

Error in xml_children(x)[[search]] : subscript out of bounds

9.29 快速定位,加上#

例如找 archive写入# archive, 就可以避开正文里面含有archive的。

9.30 表格显示

Hi 晓松,

表格问题,我晚上看了一下。

yaml处设置,

output: html_document: df_print: paged

或者

output: html_notebook

都是可以实现这种可以换页的表格展示方法。

因此你可以尝试下,如果不行我猜是你电脑的版本问题。

那么我建议你使用两个包。

kable("html") %>% 
kable_styling() %>% 

这两个函数可以完成比较美观的表格展示。

9.31 用于展示

RMarkdown实现静态网页,用于展示,只read_*include_*,不要跑过程代码,

  1. 费时
  2. 容易出bug
  3. cache=T,导致结果不能更新。

9.32 paged_table

  1. 当行数很多,但又必须全部展示的时候,可以使用rmarkdown::paged_table
    1. options = list(rows.print = 15)可以限定展示的行数(Allaire 2018)
  2. 当然也可以展示DT::datatable,但是会占用很多CPU,R session 会闪退。

参考文献

Allaire, J. J. 2018. “Tables: Display Data in Attractive, Compact Formats.” Radix for R Markdown. 2018. https://rstudio.github.io/radix/tables.html.

CSDN. 2017. “Latex 求和求乘积,积分微分等.” 2017. https://blog.csdn.net/uncle_gy/article/details/78772893.

Datta, Dilip. 2017. LaTeX in 24 Hours: A Practical Guide for Scientific Writing. 1st ed. Springer International Publishing.

Frank, Sascha. 2012. “LaTeX Arrows.” 2012. http://www.sascha-frank.com/Arrow/latex-arrows.html.

Hughes, Chris. 2012. “How to Write Conditional Equations with One-Sided Curly Brackets.” 2012. https://tex.stackexchange.com/questions/47170/how-to-write-conditional-equations-with-one-sided-curly-brackets.

Köhler, Norbert. 2018. “R Markdown: How to Number and Reference Tables.” 2018. https://datascienceplus.com/r-markdown-how-to-number-and-reference-tables/.

Loretan, Mico. 2011. “Symbol About Not Orthogonality in Latex.” Stack Exchange. 2011. https://tex.stackexchange.com/questions/27651/symbol-about-not-orthogonality-in-latex.

MacFarlane, John. 2018. “Pandoc User’s Guide.” 2018. http://pandoc.org/MANUAL.html.

Martin, Tiernan. 2017. “Incorrect Tibble Formatting.” 2017. https://github.com/rstudio/bookdown/issues/326.

Matthes, Alain. 2011. “3 Dots in Matrix.” 2011. https://tex.stackexchange.com/questions/32217/3-dots-in-matrix.

Robbins, Jennifer. 2018. Learning Web Design: A Beginner’s Guide to Html, Css, Javascript, and Web Graphics. O’Reilly Media. https://www.amazon.com/Learning-Web-Design-Beginners-JavaScript/dp/1491960205.

RStudio, Inc. 2018. “HTML Documents.” RStudio.

Stack Exchange. 2012. “Nice-Looking P-Th Roots.” 2012. https://tex.stackexchange.com/questions/3587/how-can-i-use-bibtex-to-cite-a-web-page.

Wikibooks. 2014. “LaTeX-Wörterbuch: Mathbb — Wikibooks, Die Freie Bibliothek.” https://de.wikibooks.org/w/index.php?title=LaTeX-W%C3%B6rterbuch:_mathbb&oldid=694939.

Xie, Yihui. 2016. Bookdown: Authoring Books and Technical Documents with R Markdown. Boca Raton, Florida: Chapman; Hall/CRC. https://bookdown.org/yihui/bookdown.

———. 2018a. “Create a Presentation in Powerpoint.” 2018. https://community.rstudio.com/t/create-a-presentation-in-powerpoint/9680/5.

———. 2018b. “TinyTeX - a Lightweight, Cross-Platform, Portable, and Easy-to-Maintain Latex Distribution Based on Tex Live.” 2018. https://yihui.name/tinytex/.

Yihui Xie, Garrett Grolemund, J. J. Allaire. 2018. “R Markdown: The Definitive Guide: 4.4 Powerpoint Presentation.” 2018. https://bookdown.org/yihui/rmarkdown/.

Zhu, Hao. 2018. “Create Awesome Html Table with Knitr::Kable and kableExtra.” 2018. https://cran.r-project.org/web/packages/kableExtra/vignettes/awesome_table_in_html.html.

朱昊. 2018. “用kableExtra做牛*的表格.” kableExtra. 2018. http://haozhu233.github.io/kableExtra/awesome_table_in_html_cn.html.


  1. 这是脚注的第一行。

    缩进两格子这一行会跟着脚注的第一行。

    a + b = a + b # 缩进4格,这里产生一行代码