在编织为 PDF 时,我无法调整
column_spec()
表格中 KableExtra
中的列宽。我想知道它是否与我应用于 cnames
参数的 col.names =
对象有关。返回的错误是:
我这么说的原因是调整只有第 1 列的宽度可以正常工作,并且该列的标题中没有 LaTeX 代码。我确实需要保留
cnames
对象,因为需要在实际数据的标题中包含分布在两行上的测量单位。
下面是一些示例代码来复制该错误。真心希望有人能有解决办法。谢谢!
---
title: >
`\vspace{-1.8cm}`{=latex}
header-includes:
- \usepackage{geometry}
- \geometry{margin=0.2in}
- \usepackage[default]{sourcesanspro}
- \usepackage[T1]{fontenc}
- \usepackage{makecell}
- \usepackage{fancyhdr}
- \pagestyle{fancy}
- \usepackage[export]{adjustbox}
- \fancyhf{}
- \pagenumbering{gobble}
mainfont: SourceSansPro
output: pdf_document
editor_options:
chunk_output_type: console
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
echo = FALSE,
message = FALSE,
warning = FALSE,
dev = "cairo_pdf"
)
```
```{r}
library(kableExtra)
set.seed(10)
df <- data.frame(
activity = paste("Activity", 1:10),
var1 = round(rnorm(10, 1000, 500)),
var2 = round(rnorm(10, 1000, 500)),
var3 = round(rnorm(10, 1000, 500))
)
cnames <- c(
"Period",
"\\makecell[ct]{Time\\\\(mins)}",
"\\makecell[ct]{Volume\\\\(m)}",
"\\makecell[ct]{Speed\\\\(s)}"
)
kbl(df,
booktabs = TRUE,
escape = FALSE,
col.names = cnames,
align = c("l", rep("c", ncol(df) - 1)),
linesep = "\\addlinespace") %>%
kable_styling(latex_options = c("HOLD_position"),
font_size = 8) %>%
column_spec(column = 1, width = "2in") %>%
column_spec(column = c(2:4), width = "1in")
```
这有点麻烦,但在
cnames
内设置单元格宽度显然是有效的。由于某种原因,需要单元格文本内的显式 \centering
命令和 align
中的 kbl
参数才能产生所需的对齐方式。
cnames <- c(
"\\makecell[{{p{2in}}}]{Period}",
"\\makecell[{{p{1in}}}]{\\centering Time\\\\(mins)}",
"\\makecell[{{p{1in}}}]{\\centering Volume\\\\(m)}",
"\\makecell[{{p{1in}}}]{\\centering Speed\\\\(s)}"
)
kbl(df,
booktabs = TRUE,
escape = FALSE,
col.names = cnames,
align = c("l", rep("c", ncol(df) - 1)),
linesep = "\\addlinespace") %>%
kable_styling(latex_options = c("HOLD_position"),
font_size = 8)
希望对您有用!
我的规格:
> packageVersion("kableExtra")
[1] ‘1.3.4’
> packageVersion("knitr")
[1] ‘1.45’
> sessionInfo()
R version 4.3.2 (2023-10-31)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 22.04.3 LTS