r - 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>
细节:
- 使用 knitr 1.20
- RStudio 服务器 1.1.453
- 请注意,删除
format = "html"
并不能解决问题,因为在现实生活中我想使用 css 进行高级格式化,例如基于生成的表的类
基于迈克尔哈珀接受的答案的快速解决方案可能是这样的方法:
replacechars <- function(x) UseMethod("replacechars")
replacechars.default <- function(x) x
replacechars.character <- function(x) {
x <- gsub("(", "(", x, fixed = TRUE)
x <- gsub(")", ")", 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)
解决方案
推荐阅读
- android - 为什么 requestScope 会导致错误 12501?
- java - 带有私钥的 RSA 解码文件
- jmeter - JMeter - 执行 HTTP 请求,直到响应标头匹配
- bash - 使用 Bash 逐行读取文件
- java - 试图在子类中调用超类方法
- python-3.x - Python 3 跳转表
- symfony - Symfony 3.4 中 ArrayCollection / OneToMany 关系的类型错误
- node.js - How to control the inner join query in sequelize using node.js?
- javascript - 你如何让javascript(包括带有数组和返回的函数)在按钮点击时写入div而不转到另一个页面
- javascript - 使用 angularjs 触发 HTML 属性而不使用按钮