提问人:Ben_89 提问时间:11/12/2023 最后编辑:karelBen_89 更新时间:11/15/2023 访问量:34
在 R Markdown 中编织到 PDF 时,KableExtra 列宽不起作用
KableExtra column width not working when knitting to PDF in R Markdown
问:
编织为 PDF 时,我无法调整表格中的列宽。我想知道它是否与我应用于参数的对象有关。返回的错误是:column_spec()
KableExtra
cnames
col.names =
! Paragraph ended before \mcell@tabular was complete.
<to be read again>
\par
1.129
Execution halted Error: LaTex failed to compile TestDoc.tex.
See https://yihui.org/tinytex/r/#debugging for debugging tips.
See TestDoc.log for more info.
Execution halted.
我之所以这么说,是因为只有第 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")
```
答:
1赞
Julian Selke
11/12/2023
#1
这有点麻烦,但设置内部的单元格宽度显然是有效的。出于某种原因,单元格文本中的显式命令和参数都需要生成所需的对齐方式。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
评论
0赞
Ben_89
11/12/2023
哦,谢谢!我确实想知道是否可以设置宽度。感谢它!cnames
评论