首页 > 解决方案 > knitr 将 (1) 更改为

    渲染html时?

问题描述

.Rmd 文件的以下内容:

---
title: "Untitled"
output:
  html_document: default
---

```{r cars}
mtcars$am <- sprintf("(%s)", as.character(mtcars$am))
knitr::kable(mtcars, format = "html")
```

在呈现为 html 后,将<ol><li></li></ol>在列中显示有序列表am,而不是括号中的数字(如 生成)。sprintf

这是故意的吗?我该如何解决这个问题并让括号中的数字显示为 html 输出中的数字?

的输出knitr::kable似乎很好,显示:

<td style="text-align:left;"> (1) </td>

细节:

基于迈克尔哈珀接受的答案的快速解决方案可能是这样的方法:

replacechars <- function(x) UseMethod("replacechars")
replacechars.default <- function(x) x
replacechars.character <- function(x) {
  x <- gsub("(", "&lpar;", x, fixed = TRUE)
  x <- gsub(")", "&rpar;", x, fixed = TRUE)
  x
}
replacechars.factor <- function(x) {
  levels(x) <- replacechars(levels(x))
  x
}
replacechars.data.frame <- function(x) {
  dfnames <- names(x)
  x <- data.frame(lapply(x, replacechars), stringsAsFactors = FALSE)
  names(x) <- dfnames
  x
}

示例使用:

mtcars <- datasets::mtcars

# Create a character with issues
mtcars$am <- sprintf("(%s)", as.character(mtcars$am))

# Create a factor with issues
mtcars$hp <- as.factor(mtcars$hp)
levels(mtcars$hp) <- sprintf("(%s)", levels(mtcars$hp))

replacechars(mtcars)

标签: rr-markdownknitrkable

解决方案


如果您不想删除format="html"参数,可以尝试使用 HTML 字符实体作为括号(&lpar&rpar),然后添加参数escape = FALSE

```{r cars}
mtcars$am <- sprintf("&lpar;%s&rpar;", as.character(mtcars$am))
knitr::kable(mtcars, format = "html", escape = FALSE)
```

在此处输入图像描述

尽管如此,仍然不能完全确定是什么导致了错误。似乎knitr正在奇怪地处理括号的特定组合。


推荐阅读