如何使用列和行名称或索引为R中的数据表(DT包)中的单元格背景着色? [英] How to color the background of a cell in datatable (DT package) in R with column and row names or indices?
问题描述
这里是一个例子。我创建了一个数据框,并使用它来创建用于可视化的数据表。如您所见,我的列名和第一列中的行指示A和B中的条件。我要做的是更改此数据表中特定单元格的背景色。如该链接所述(
我不确定问题,但是如果您想更改其行索引和列索引给定的单元格的背景颜色(这是我的理解),则可以执行以下操作:
changeCellColor<-函数(行,列){
c(
函数(行,数据,数字,索引){,
sprintf( (index ==%d){,row-1),
sprintf( $('td:eq('+%d +')',row),col),
.css({'background-color':'orange'});;,
},
}
)
}
datatable(dat ,
options = list(
dom = t,
rowCallback = JS(changeCellColor(1,2))
)
)
Here is an example. I created a data frame and use that to create a datatable for visualization. As you can see, my column name and the row from the first column indicate conditions from A and B. What I want to do is to change the background color of a specific cell in this datatable. It is easy to select the column to change, as explained in this link (https://rstudio.github.io/DT/010-style.html). However, it is not obvious to me how to specify the row I want to select.
To give you more context, I am developing a Shiny
app, and I would like to design a datatable allow me to color a cell based on the condition from A
and B
. For example, if A is less than 1
and B is between 1 and 2
, I would like to be able to select the second cell from the A is less than 1
column. To acheive this, I will need to know how to specify the row number or row name. For now, I only know how to specify the rows based on the contents in the rows, as this example shows.
library(tibble)
library(DT)
dat <- tribble(
~`A/B`, ~`A is less than 1`, ~`A is between 1 and 2`, ~`A is larger than 2`,
"B is less than 1", 10, 30, 30,
"B is between 1 and 2", 20, 10, 30,
"B is larger than 2", 20, 20, 10
)
datatable(dat, filter = "none", rownames = FALSE, selection = "none",
options = list(dom = 't', ordering = FALSE)) %>%
formatStyle(
'A is less than 1',
backgroundColor = styleEqual(20, "orange")
)
I'm not sure to get the question, but if you want to change the background color of a cell given by its row index and its column index (that's what I understand), you can do:
changeCellColor <- function(row, col){
c(
"function(row, data, num, index){",
sprintf(" if(index == %d){", row-1),
sprintf(" $('td:eq(' + %d + ')', row)", col),
" .css({'background-color': 'orange'});",
" }",
"}"
)
}
datatable(dat,
options = list(
dom = "t",
rowCallback = JS(changeCellColor(1, 2))
)
)
这篇关于如何使用列和行名称或索引为R中的数据表(DT包)中的单元格背景着色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!