[英]Edit RGB colors of Cells in Data Table (R)
I am working on a project that includes a data table.我正在开发一个包含数据表的项目。 I would like the data table cells to be colored by similar values in a column.
我希望数据表单元格由列中的相似值着色。 I am struggling to understand how to modify the code below to be able to choose colors in my data table.
我很难理解如何修改下面的代码以便能够在我的数据表中选择 colors。 The code was taken from another example I found on Stackoverflow:
代码取自我在 Stackoverflow 上找到的另一个示例:
set.seed(1)
df <- cbind.data.frame(matrix(round(rnorm(50), 3), 10), sample(0:1, 10, TRUE))
brks <- apply(df, 2, quantile, probs=seq(.05, .95, .05), na.rm=T)
clrs <- apply( brks, 2, function(x) round(seq(255, 40, length.out = length(x)+1), 0)
%>% {paste0("rgb(255,", ., ",", ., ")")})
eval(parse(text=paste0("datatable(df) ", paste(sapply(1:ncol(df), function(i)
paste0("%>% formatStyle(names(df)[",i,"], backgroundColor = styleInterval(brks[,",i,"],
clrs[,",i,"]))") ), collapse = " " ))))
I don't understand how to modify the clrs line and the rgb function in paste0 to get the colors that I want.我不明白如何修改 clrs 行和 paste0 中的 rgb function 以获得我想要的 colors。 I have tinkered around with both of these chunks, but can not figure out how it works.
我已经修改了这两个块,但无法弄清楚它是如何工作的。 Can someone explain to me how I can exactly specify a color using the above code.
有人可以向我解释如何使用上面的代码准确指定颜色。 If I wanted to get the color blue or green or fade from one color to another, how would I go about doing that?
如果我想获得蓝色或绿色或从一种颜色褪色到另一种颜色,我将如何 go 这样做?
I am very stuck.我很困。 Any help would be appreciated!
任何帮助,将不胜感激! Thank you!
谢谢!
First eval
is used to evaluate a name, a call or other... In this case it is a name.第一个
eval
用于评估名称、呼叫或其他...在这种情况下,它是一个名称。 I propose a simpler code which I can explain each part, it will be your part to adapt it:我提出了一个更简单的代码,我可以解释每个部分,这将是你调整它的部分:
library(DT)
# the dataset
df <- cbind.data.frame(matrix(round(rnorm(50), 3), 10))
# the color wanted
sample_color <- data.frame(col1 = c(0.2, 0.1, 0.6),
col2 = c(0.5, 0.1, 0.3))
datatable(df) %>%
formatStyle('1', color = eval(call(name = "rgb",
matrix(sample_color$col1, ncol = 3))))
We need to use matrix
because of that .因此我们需要使用
matrix
。 The eval
and call
are only base R that you will probably better understand if you directly goes to their presentation pages: eval , call . eval
和call
只是基本的 R 如果你直接去他们的演示页面你可能会更好地理解: eval , call 。
EDIT 1 Change the backgroung color of a datatable cell编辑 1 更改数据表单元格的背景颜色
datatable(df) %>%
formatStyle('1', color = eval(call(name = "rgb",
matrix(sample_color$col1, ncol = 3))),
backgroundColor = eval(call(name = "rgb",
matrix(sample_color$col1, ncol = 3))))
Look at the package vignette of DT to better understand how it works.查看DT的 package 小插图,以更好地了解其工作原理。 There is a section formatCurrency which is suited for you.
有一个部分 formatCurrency 适合您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.