我希望表格在一列中有项目符号并具有特定的表格宽度(以便在呈现为 PDF 时放置在一页上)。
我怎样才能在 rmarkdown
中实现这一点?使用那里的众多软件包之一?
到目前为止我已经尝试过的和拥有的:
---
output: pdf_document
---
```{r, include = FALSE}
df <- data.frame(col1 = "Some really long text here. I mean some reeeeeaaly loooong text. So long, it should be wrapped. Really.",
col2 = "* bullet point 1\n * bullet point 2", col3 = "Yes, there is still another column.")
```
# Attempt 1: kableExtra
```{r, echo = FALSE, warning = FALSE}
library(kableExtra)
df1 <- df
df1$col2 <- linebreak(df1$col2)
knitr::kable(df1, escape = FALSE) %>% column_spec(1, width = "15em")
```
# Attempt 2: pander
```{r, echo = FALSE}
pander::pander(df, keep.line.breaks = TRUE, style = 'grid', justify = 'left')
```
这呈现为:
如您所见,这两个选项都有警告。
kableExtra
版本确实具有适合一页的特定表格宽度,但不能很好地显示项目符号。而pander
解决方案很好地呈现项目符号但跨越多个页面,因为我不知道如何在 pander
中指定表格宽度.有没有可以两者兼顾的解决方案?
相关问题例如 here和 there .
最佳答案
基于 kableExtra 的替代解决方案(可选:带脚注)
这种方法允许添加标题、在表格中手动添加脚注以及固定列宽。
要创建项目符号列表:
\cdots
来自 LaTex 被用作子弹 (alternatives see here) \n
强制换行(因此缩进不如@daroczig 的pander
方法好)。 MWE
library(stringi); library(kableExtra); library(dplyr)
string_short <- "Descriptor"
string_long <- substr(stri_rand_lipsum(1), 1, 50)
# add footnotes manually within table
string_bulletlist <- "$\\boldsymbol{\\cdot}$ bullet point 1: foo$^{a}$ \n $\\boldsymbol{\\cdot}$ bullet point 2: bar$^{b}$"
df <- data.frame(col1 = c(string_short, string_short),
col2 = c(string_bulletlist, string_bulletlist),
col3 = c(string_long, string_long)
)
col_names <- c("Descriptor", "Description with list", "Some comment")
# header: bold column names
colnames(df) <- paste0("\\textbf{", col_names,"}")
# add footnote with kableExtra commands
names(df)[1] <- paste0(names(df)[1], footnote_marker_symbol(1))
df %>%
mutate_all(linebreak) %>% # required for linebreaks to work
kable(
"latex",
escape = F,
booktabs=TRUE,
align = "l",
caption = 'kableTable with bullet list and footnote') %>%
# kable_styling(full_width = F) %>% # makes no difference here
footnote(general = "General comment of the table.",
alphabet = c("Footnote A;", "Footnote B;"),
symbol = c("Footnote Symbol 1")) %>%
column_spec(1, width = "5em") %>% # fix width column 1
column_spec(2, width = "10em") %>% # fix width column 2
column_spec(3, width = "15em") # fix width column 3
为了[提高行间距[(https://stackoverflow.com/questions/53794142/increase-line-row-spacing-with-kableextra),可以在 Rmd 中的代码块之前和之后添加以下内容:\renewcommand{\arraystretch}{1.5} <!-- increase line spacing for the table -->
RMD CHUNK HERE
\renewcommand{\arraystretch}{1} <!-- reset row hight/line spacing -->
评论:
我也试过
pander
来自@daroczig 的方法并取得了以下经验:$\boldsymbol{\cdot}$
相比 kableExtra
方法中的解决方法)。 此外,当使用
pander
在 Rmd 文件中使用 huskydown thesis template脚注极大地弄乱了表格的对齐方式。
关于r - 带有长文本、项目符号和特定表格宽度的表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52962411/