使用"\ n"将文本包装在knitr :: kable表单元格中 [英] wrap text in knitr::kable table cell using "\n"
问题描述
如何使用\n
将单元格包装在knitr::kable
表单元格中?
How can I wrap a cell in a knitr::kable
table cell using \n
?
我想生成一个.rmd文件,其中包含一些表,其中一列需要换行.包装应发生的地方用\n
标记.我尝试过(这是一个独立的.rmd文件):
I want to generate a .rmd file containing some tables where one column needs text wrapping. The places where the wrapping should occur are marked with \n
. I tried (this is a standalone .rmd document):
---
output: pdf_document
---
## A Table with text wrap
```{r cars}
knitr::kable(data.frame(col1 = c("a", "b"), col2 = c("one\ntwo", "three\nfour")))
```
..但这不起作用.包裹的部分将保留在col1
的下一行中,而不是留在col2
中.
..but this doesn't work. Instead of staying in col2
, the wrapped part lives on the next line of col1
.
预期输出为:
col1 | col2
-------------
a | one
| two
b | three
| four
欢迎使用除knitr
以外的其他程序包的解决方案,只要它们允许(几乎)打印出精美的图像即可.
Solutions using other packages than knitr
are welcome as long as they allow to print (nearly) as nice.
推荐答案
一劳永逸的解决方案,用于标准表的灵活双HTML/PDF.它包含了@snoram概述的kableExtra的换行功能.
假设:您将<br>
用作换行指示器.
A fire-and-forget solution for flexible dual HTML/PDF of standard tables. It incorporates kableExtra's linebreak function outlined by @snoram.
Assumption: You use <br>
as your line break indicator.
```{r}
knit_table(df1)
```
library(dplyr)
library(knitr)
library(kableExtra)
knit_table <- function(df){
if (is_html_output()) {
df %>%
kable("html", escape = F) %>%
kable_styling()
} else {
df <- data.frame(lapply(df, function(x) {gsub("<br>", "\n", x)}), stringsAsFactors = F)
df %>%
mutate_all(linebreak) %>%
kable("latex", booktabs = T, escape = F)
}
}
数据
df1 <- data.frame(col1 = c("a", "b"),
col2 = c("one<br>two", "three<br>four"))
这篇关于使用"\ n"将文本包装在knitr :: kable表单元格中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!