我正在尝试格式化数据框的数字列,其中列类型包括日期、字符和双精度(即数字)。
当我在像 iris 这样的数据帧上使用 formattable 包时,我得到了预期的结果。但是,当我在我的数据框上使用它时,我没有得到预期的结果(数字没有根据值正确格式化)。
这是一个带有简单虚拟数据的可重现示例:
# Load packages
library(tidyverse)
library(formattable)
# Create formattable function to conditionally format numbers. If > 5, make green...
sign_formatter <- formatter("span",
style = x ~ style(color = ifelse(x > 5, "green",
ifelse(x < 5, "red", "black")
)
)
)
# Formats as expected on iris data frame, other than makes Species column green (and maybe not if the 5.0 in iris is exactly 5, then this should format with the color black):
formattable(iris, list(~ sign_formatter))
# Create data frame to replicate type of data frame I have
my_class = LETTERS[1:3]
my_dates = seq(as.Date("2019/01/01"), by = "day", length.out = 3)
my_nums1 = c(1, 5, 10)
my_nums_2 = c(-5, 0, 7)
my_df <- data.frame(my_class, my_dates, my_nums1, my_nums_2)
# Does not format as expected
formattable(my_df, list(~ sign_formatter))
# Formats correctly if I select numeric columns only, but of course I lose the other columns given use of select_if:
formattable(my_df %>%
select_if(., is.numeric), list(~ sign_formatter))
问题: 为什么 formattable 在示例数据框上不起作用,在这种情况下如何在不单独指定每列的格式(或在使用 select_if 时不返回数字列)的情况下使其工作?
谢谢您的帮助!