我需要在RMarkdown中创建多个表,并使用kableExtra包设置其样式。例如,我有虹膜数据集。我的第一张表显示前20行,第二张表显示后20行,第三张表显示20行...以下是代码:
---
title: ""
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r}
library(knitr)
library(kableExtra)
landscape(kable_styling(kable(iris[1:20, ], format = "latex", align = "c",
row.names = FALSE), latex_options = c("striped"), full_width = T))
landscape(kable_styling(kable(iris[21:40, ], format = "latex", align = "c",
row.names = FALSE), latex_options = c("striped"), full_width = T))
landscape(kable_styling(kable(iris[41:60, ], format = "latex", align = "c",
row.names = FALSE), latex_options = c("striped"), full_width = T))
```
效果很好,它返回三个表,每个表在不同的工作表中。实际上,我不仅有三个表,因此我认为使用for循环会更明智,并且利用了此链接R: why kable doesn't print inside a for loop?中给出的答案。很简单,我会按照建议在每个打印呼叫后放置一个换行符。
---
title: "untitled"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r}
library(knitr)
library(kableExtra)
for (i in 1:3) {
print(landscape(kable_styling(
kable(iris[20*(i-1)+1:20*i, ], format = "latex", align = "c",
row.names = FALSE), latex_options = c("striped"), full_width = T)))
cat("\n")
}
```
但是它不起作用。我猜这是因为我用kableExtra包中的命令封装了kable命令。
有谁可以使它起作用?我的意思是有什么方法可以使我免于打字吗?
答案 0 :(得分:2)
您现有的代码就在附近。我认为唯一需要做的更改是在块选项中添加results='asis'
(我认为不需要多余的换行符)。这是适用于我的完整RMarkdown内容
---
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r results='asis'}
library(knitr)
library(kableExtra)
for (i in 1:3) {
print(landscape(kable_styling(
kable(iris[20*(i-1)+1:20*i, ], format = "latex", align = "c",
row.names = FALSE), latex_options = c("striped"), full_width = T)))
}
```