r - 一次将可格式化的格式应用于所有列
问题描述
我想将数据框转换为可格式化的表格,并为每一列添加自定义格式。有没有办法将格式应用于所有列而不专门调用它们?这是一些示例代码,说明了我目前拥有的内容:
library(formattable)
# create df
col1 <- c(0, -2, 4)
col2 <- c(-1, 0, 2)
col3 <- c(-1, -1, 0)
df <- data.frame(col1, col2, col3)
# set colors
red <- "#ff7f7f"
blue <- "#7f9dff"
white <- "#ffffff"
# add custom format
color_format <- formatter('span',
style = x ~ style(color = ifelse(x > 0, blue,
ifelse(x < 0, red, white))))
# create table
formattable(df,
list("col1" = color_format,
"col2" = color_format,
"col3" = color_format))
我还有几列,它们的名称有时会改变,所以我需要一种不手动调用每一列的方法。
解决方案
尝试使用lapply
myForm <- function(x) {
formatter('span',
style = x ~ style(
color = ifelse(x > 0, blue,
ifelse(x < 0, red, white))
))
}
formattable(df, lapply(df, myForm))
推荐阅读
- javascript - 将点击事件保存在本地存储中
- bash - docker-compose postgresql 自定义初始化脚本错误
- fivem - FiveM 服务器错误 Linux ubuntu 18.04 Yarn
- php - 在 Nginx docker 容器中创建虚拟主机
- javascript - SVELTE 中即时搜索和列表选择的几个问题
- angular - 使用 vscode 在打字稿上每个文件夹的不同配置
- typescript - 如何在 TypeScript 中重载可选布尔值
- java - “mvn链接”依赖项的最佳方式?
- php - codeigniter 4中生产模式下的数据库错误句柄
- bash - 使用 AWK 从目录搜索和过滤器中打印两个不同的结果