我有以下数据框:
df <- data.frame(col1 = letters[1:10],
col2 = c(0, 0.52, 0.93, 2, 10, 51, 523, 52353, 623464, 12356833538))
我想在 HTML R markdown 文件中显示带有
DT
包的数据框,其中 col2
应如下图所示显示,但保留其数字类:
因为我想保留
DT
中的过滤功能。但是,目前我正在使用 sub
和 formatC
强制以我想要的方式显示列,这使其具有特征,因此丢失了 DT
中的过滤滑块。
library(DT)
library(tidyverse)
df2 <- df %>% mutate(col2 = ifelse(col2 <= 10,
formatC(col2, format = "f", digits = 2),
sub("e\\+0?(\\d+)", " x 10<sup>\\1</sup>", formatC(col2, format = "e", digits = 2))))
datatable(df2, escape = F, rownames = FALSE,
filter = list(position = "top", clear = F, plain = F))
这是我想要的滑块功能:
因此,我想知道如何在 HTML R markdown 文档中显示带有指数的列,同时保留数字属性(或保留
DT
滑动过滤器功能)。
我不确定是否有可能实现我想要的,所以任何意见将不胜感激。
您可以尝试使用
formattable
包来 create formattable numeric vector.
---
title: "Formattable & DT"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message=FALSE, warning = FALSE)
```
```{r}
df <- data.frame(col1 = letters[1:10],
col2 = c(0, 0.52, 0.93, 2, 10, 51, 523, 52353, 623464, 12356833538))
```
```{r}
library(DT)
library(formattable)
library(tidyverse)
format_postproc <- function(x) {
if_else(x <= 10,
formatC(x, format = "f", digits = 2),
sub("e\\+0?(\\d+)", " x 10<sup>\\1</sup>", formatC(x, format = "e", digits = 2))
)
}
fm_dt <- formattable(df, list(
col2 = format_postproc
))
as.datatable(fm_dt , rownames = FALSE,
filter = list(position = "top", clear = F, plain = F))
```