简体   繁体   中英

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. The code was taken from another example I found on 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. 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?

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. 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 . The eval and call are only base R that you will probably better understand if you directly goes to their presentation pages: eval , call .

EDIT 1 Change the backgroung color of a datatable cell

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. There is a section formatCurrency which is suited for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM