R:根据给定值为 table 中的单元格着色
R: Color cells in a table based on the given value
我有一个 table,数字为 1-10。它看起来像这样:
现在我想用不同颜色为每个整数填充单元格。
例如,所有值为 1 的单元格应为红色,2 为黑色......等等。
你有什么建议如何实现这一目标?
非常感谢。
确实存在可以执行此操作的软件包。目前接口最直接的包大概就是condformat
使用condformat::rule_file_discrete
功能了。不幸的是,我没有可用的示例,因为我 condformat
需要 rJava
,这与我的系统不兼容。
pixiedust
包(完全公开,我是作者)可以做到这一点,但目前不是很直接。
library(pixiedust)
library(scales)
library(magrittr)
# Make the table (as a matrix, but a data frame would work as well)
set.seed(pi)
X <- matrix(sample(1:10,
size = 100,
replace = TRUE),
nrow = 10)
# Define 10 colors
background <- hue_pal()(10) %>%
setNames(1:10)
show_col(background)
# Convert X to a dust object
X_dust <- dust(X)
# Apply the background colors
for (i in sort(unique(as.vector(X)))){
X_dust <-
sprinkle(X_dust,
rows = X_dust$body$row[X_dust$body$value == i],
cols = X_dust$body$col[X_dust$body$value == i],
bg = background[i],
fixed = TRUE)
}
# Print the HTML code
X_dust %>%
sprinkle_print_method("html")
我目前正在开发仅需几行代码即可完成此操作的代码,但该功能尚未准备好发布。
我有一个 table,数字为 1-10。它看起来像这样:
现在我想用不同颜色为每个整数填充单元格。 例如,所有值为 1 的单元格应为红色,2 为黑色......等等。 你有什么建议如何实现这一目标? 非常感谢。
确实存在可以执行此操作的软件包。目前接口最直接的包大概就是condformat
使用condformat::rule_file_discrete
功能了。不幸的是,我没有可用的示例,因为我 condformat
需要 rJava
,这与我的系统不兼容。
pixiedust
包(完全公开,我是作者)可以做到这一点,但目前不是很直接。
library(pixiedust)
library(scales)
library(magrittr)
# Make the table (as a matrix, but a data frame would work as well)
set.seed(pi)
X <- matrix(sample(1:10,
size = 100,
replace = TRUE),
nrow = 10)
# Define 10 colors
background <- hue_pal()(10) %>%
setNames(1:10)
show_col(background)
# Convert X to a dust object
X_dust <- dust(X)
# Apply the background colors
for (i in sort(unique(as.vector(X)))){
X_dust <-
sprinkle(X_dust,
rows = X_dust$body$row[X_dust$body$value == i],
cols = X_dust$body$col[X_dust$body$value == i],
bg = background[i],
fixed = TRUE)
}
# Print the HTML code
X_dust %>%
sprinkle_print_method("html")
我目前正在开发仅需几行代码即可完成此操作的代码,但该功能尚未准备好发布。