在knitr中打印字符向量作为LaTeX列表

时间:2016-03-14 14:14:46

标签: r latex knitr

是否有选项或函数采用这样的矢量

c("toto", "tata" ,"tutu", "toto", "coco")

并生成一个LaTeX列表,如:

\begin{itemize}
      \item toto
      \item tata
      \item tutu
      \item coco
\end{itemize}

1 个答案:

答案 0 :(得分:3)

可能有一个库,但我不知道。目前,以下辅助函数在大多数情况下都应该起作用:

printList <- function(x, out.format = knitr::opts_knit$get("out.format"),
                      environment = "itemize",
                      marker = NULL) {
  if (out.format == "markdown") {
    if (!missing(environment) || !missing(marker)) {
      warning("Ignoring arguments that are not supported for markdown output.")
    }
    out <- sprintf("\n\n%s\n \n", paste("*", x, collapse = "\n"))
  } else {
    if (out.format == "latex") {
      itemCommand <- if (missing(marker)) {
        "\\item"
      } else {
          sprintf("\\item[%s]", marker)
      }
      listEnv <- c(
        sprintf("\\begin{%s}\n", environment),
        sprintf("\n\\end{%s}\n", environment))
      out <- paste(itemCommand, x, collapse = "\n")
      out <- sprintf("%s%s%s", listEnv[1], out, listEnv[2])
    } else {
      stop("Output format not supported.")
    }
  }
    return(knitr::asis_output(out))
}
@

它可以生成markdown和LaTeX输出并自动检测输出格式(knitr::opts_knit$get("out.format"))。

对于markdown,仅支持带有项目符号的简单列表。使用LaTeX输出时,默认列表环境为itemize,但可以使用environment指定任何其他环境。如果设置marker(假设长度与x相同),则将其用作\item的可选参数。

该功能可以在块和内联中使用。

演示

(将上面的定义复制到文档中!):

RNW:

\documentclass{article}
\begin{document}
<<>>=
# insert definition!
@

<<results = "asis">>=
printList(LETTERS[1:3])
printList(LETTERS[1:3], environment = "enumerate")
printList(LETTERS[1:3], marker = LETTERS[24:26])
@

Inline: \Sexpr{printList(LETTERS[1:3])}
\end{document}

RMD:

```{r}
# insert definition!
```

```{r}
printList(LETTERS[1:3])
printList(LETTERS[1:3], environment = "enumerate") # warning
printList(LETTERS[1:3], marker = LETTERS[24:26]) # warning
```

Inline: `r printList(LETTERS[1:3])`
相关问题