我正在使用 {gt} 包在报告中创建表。我希望将“$0.00”货币值替换为“-”,这在 Excel 中很容易做到,但在 {gt} 中似乎很难做到。这是一个表格示例,我希望将零值替换为更容易看到的东西。我能做的最好的事情就是使用fmt并制作一个自定义函数来重新创建 的全部功能fmt_currency,这看起来不太好。
library(gt)
library(magrittr)
data <- data.frame(x=c(1.23,4.56,0,0,0,0,0))
table <- gt(data) %>%
fmt_currency(x)
Run Code Online (Sandbox Code Playgroud)
当然,其他反应也很棒。我喜欢通过使用gt::fmt()通用格式化函数而不是gt::fmt_currency().
library(gt)
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 <-
data %>%
gt() %>%
fmt(
columns = everything(),
fns = function(x) ifelse(x == 0, "—", scales::dollar(x, accuracy = 0.01))
)
Run Code Online (Sandbox Code Playgroud)
由reprex 包(v2.0.1)于 2021 年 8 月 24 日创建
我认为这gt::text_transform()可以解决您眼前的问题。
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){
"-"
}
)
Run Code Online (Sandbox Code Playgroud)
如果您想跨多个列执行此操作,您可能还需要将其包装到一个函数中并针对特定列进行调用。
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)
Run Code Online (Sandbox Code Playgroud)
但是您可能更适合将逻辑放入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))
)
Run Code Online (Sandbox Code Playgroud)