I have a Rmarkdown document in which I need to produce a table. The table has several columns, some of which are currency and some others are percentages. I need to produce a pdf output.
This will be enough:
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))
I'm aware I can format each column for what I need, like this:
kable(df[, .(x, paste0("$", round(y, 0)), paste0(round(100 * z, 1), "%"))
Also, if I had html output instead of pdf, I could do something like
library(DT)
datatable(df) %>% formatCurrency(columns = 2, digits = 0) %>% formatPercentage(columns = 3, digits = 1)
I can't use the DT::datatable
approach, as my output is pdf, and DT doesn't produce pdf / latex output.
I wouldn't like to use the kable
approach, as it would be cumbersome to produce paste0
code for each different case.
An option similar to the DT
approach that produces pdf output.
How can I achieve that?
Following @Axeman's advice, there are at least alternatives to use with scales
and formattable
packages:
# 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))])