如何解决 RMarkdown pdf 中与复杂居中字幕相关的错误

如何解决 RMarkdown pdf 中与复杂居中字幕相关的错误

我正在使用 RMardown,并尝试添加一个包含模型语法的居中字幕,我将在该部分展示

---
title: "example"
author: "X"
date: "2023-09-23"
output: pdf_document
---

\newcommand{\csubsubsection}[1]{
  \hypertarget{#1}{%
  \subsubsection{\texorpdfstring{\centering\emph{#1}}{#1}}\label{#1}}
}

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

below after some sections....


## *Title*

\csubsubsection{Model applied: lm(x ~ y,random = ~ 1|A)}

但是我收到了这个错误。

! Missing \endcsname inserted.
<to be read again> 
                   \protect 
l.23 ...x ~ y, random = ~ 1|A)}}{section*.4}{}}

我该如何解决这个问题?谢谢

答案1

  • 小节周围的超目标既不是必要的也不是有用的,您可以通过标签链接到小节。

  • 您不应使用整个子部分标题作为标签。请选择一个您可以记住的简单字符串。您应避免在标签中使用特殊字符等。


---
title: "example"
author: "X"
date: "2023-09-23"
output: pdf_document
---

\newcommand{\csubsubsection}[2]{
  \subsubsection{\texorpdfstring{\centering\emph{#1}}{#1}}\label{#2}
}

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

below after some sections....


\csubsubsection{Model applied: $lm(x \sim y,\mathrm{random} = \sim 1|A)$}{AppliedModel}

在此处输入图片描述

答案2

没有必要那么复杂。您只需要### \centering ...### \hfil ...作为一行的标题。

要引用模型,您可以使用,[...]但为了安全和简单起见,最好添加标签(### \centering ... {#label}),然后使用[your link text](#label)

仅出于完整性考虑,MWE 测试是否隐藏目录中的模型、是否对其进行编号、是否使用全局编号或未编号的标题:


姆韦


MWE.Rmd

---
output: 
  pdf_document:
    number_sections: true
toc: true
linkcolor: blue
toccolor: magenta
---

# Section
##  Subsection
### \centering Model applied: \(lm(x \sim y,\mathrm{random} = \sim 1|A)\) { #bar}

The [model](#bar) is in page \pageref{bar} is. 
If `number_sections: false`  obviously cross-references 
to section numbers will be empty.

#### Paragraph
Bla bla ..

### \centering Model applied: \(lm(x \sim y,\mathrm{random} = \sim 1|A)\) {.unnumbered .unlisted  #foo}

The [Applied Model](#foo) in page   \pageref{foo} is unnumbered 
even with `number_sections: true` and not listed in ToC. 
In this case a cross-reference will point to the last 
numbered header (now the paragraph \ref{foo}). 

相关内容