将 table 列格式化为百分比,pdf 输出的货币 (Rmarkdown)

Format table columns as percent, currency for pdf output (Rmarkdown)

我有一个 Rmarkdown 文档,我需要在其中生成 table。 table 有几列,其中一些是货币,另一些是百分比。我需要生成 pdf 输出。

示例数据

这就足够了:

library(data.table)
df <- data.table(x = letters[1:3], y = c(10.20, 20.501, 30.3222), z = c(0.6, 0.065, 0.95))

我试过的替代品

我知道我可以根据需要格式化每一列,如下所示:

kable(df[, .(x, paste0("$", round(y, 0)), paste0(round(100 * z, 1), "%"))

此外,如果我 html 输出 而不是 pdf,我可以做类似

library(DT)
datatable(df) %>% formatCurrency(columns = 2, digits = 0) %>% formatPercentage(columns = 3, digits = 1)

我遇到的困难

我不能使用 DT::datatable 方法,因为我的输出是 pdf,而 DT 不生成 pdf/latex 输出。

我不想使用 kable 方法,因为为每个不同的案例生成 paste0 代码会很麻烦。

我想要什么:

类似于 DT 生成 pdf 输出的方法的选项。

我怎样才能做到这一点?

按照@Axeman 的建议,至少可以使用 scalesformattable 包的替代方法:

# Option 1: scales
library(scales)
kable(df[, .(x, dollar(y, accuracy = 1), percent(z, accuracy = 0.1))])


# Option 2: formattable
detach("package:scales", unload = TRUE) #function percent has the same name
library(formattable)
kable(dt[, .(x, currency(y, digits = 0), percent(z, digits = 1))])