I think that gt::text_transform()
can solve your immediate problem.
library(gt)
library(magrittr)
data <- data.frame(x=c(1.23,4.56,0,0,0,50,1.5))
table <- data %>%
gt() %>%
fmt_currency(x)
table
table %>%
text_transform(
locations = cells_body(
x,
rows = x==0
),
fn = function(x){
"-"
}
)
Multiple Columns
If you want to do it across multiple columns, you may want to also wrap it into a function and call against specific columns.
data <- data.frame(
x = c( 0, -0.230, 0, -0.445, 0),
y = c( -0.230, 0.0705, 0.460, -0.686, 0),
z = c( 0, 0, 0.07, 0.129, -0.68)
)
currency_dash <- function(gt_data, col_name) {
text_transform(
gt_data,
locations = cells_body(
columns = {{ col_name }},
rows = {{ col_name }} == 0
),
fn = function(x) {
"-"
}
)
}
data %>%
gt() %>%
fmt_currency(columns = everything()) %>%
currency_dash(x) %>%
currency_dash(y) %>%
currency_dash(z)
General Transform
But you'd likely be better suited with just putting the logic into the text_transform()
.
data <- data.frame(
x = c( 0, -0.230, 0, -0.445, 0),
y = c( -0.230, 0.0705, 0.460, -0.686, 0),
z = c( 0, 0, 0.07, 0.129, -0.68)
)
table_currency <- data %>%
gt() %>%
fmt_currency(everything())
table_currency %>%
text_transform(
locations = cells_body(),
fn = function(x) ifelse(x == "$0.00", "-", x))
)