R语言 如何在DT数据表上按多个条件为行着色

szqfcxe2  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(107)

我一直在努力解决这个问题,我似乎无法在网上找到解决方案。
我创建一个HTML表格使用DT包,我想颜色的行取决于几个条件,从多个列。
下面是我正在使用的datatable示例:

dt <- data.table(id = c("FR12", "FR02", "TR06", "FR07", "FR06", "FR77", "FR14", "FR53", "FR25", "FR59"),
                 method1 = c("Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y"),
                 method2 = c("Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", NA),
                 method3 = c("Y", NA, "Y", NA, "Y", "Y", "Y", "Y", "Y", NA),
                 method4 = c("Y", NA, NA, NA, NA, "Y", "Y", "Y", NA,  NA)
                 )

字符串
我正在使用以下代码创建一个数据表:

datatable(dt,
  options = list(paging = TRUE,   
                 pageLength = 10, 
                 scrollX = TRUE,  
                 scrollY = TRUE,   
                 autoWidth = FALSE, 
                 server = TRUE,  
                 dom = 'Bfrtip',
                 buttons = c('csv', 'excel')),
  extensions = 'Buttons',
  selection = 'single', 
  filter = 'bottom',            
  rownames = TRUE)


我设法使用以下代码对所有列都有“Y”的行进行着色:

datatable(dt,
  options = list(paging = TRUE,   
                 pageLength = 10, 
                 scrollX = TRUE,  
                 scrollY = TRUE,   
                 autoWidth = FALSE, 
                 server = TRUE,  
                 dom = 'Bfrtip',
                 buttons = c('csv', 'excel')),
  extensions = 'Buttons',
  selection = 'single', 
  filter = 'bottom',            
  rownames = TRUE) %>%
formatStyle(c("method1", "method2", "method3", "method4"), target = 'row', 
              backgroundColor = styleEqual(c("Y", NA), c('green', 'white')))


但是我想使用一个颜色梯度,从绿色到红色,根据包含“Y”值的列的数量来着色。
提前感谢您的帮助!

ktecyv1j

ktecyv1j1#

library(DT)

df <- data.frame(
  id = c("FR12", "FR02", "TR06", "FR07", "FR06", "FR77", "FR14", "FR53", "FR25", "FR59"),
  method1 = c("Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y"),
  method2 = c("Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", NA),
  method3 = c("Y", NA, "Y", NA, "Y", "Y", "Y", "Y", "Y", NA),
  method4 = c("Y", NA, NA, NA, NA, "Y", "Y", "Y", NA,  NA)
)

# get number of Ys in each row
nY <- apply(df[, 2:5], 1L, function(x) length(na.omit(x)))

# colors
clrs <- c(
  "0" = "#ff0000", 
  "1" = "#ff8c00", 
  "2" = "#fab57f", 
  "3" = "#ffff00", 
  "4" = "#00ff00"
)

# colors column
colcol <- clrs[as.character(nY)]

# add four columns each equal to nY - they will be hidden
df2 <- cbind(df, nY, nY, nY, nY)

# datatable
library(DT)
datatable(
  df2, rownames = FALSE,
  options = list(
    columnDefs = list( # hide the nY columns
      list(targets = 5:8, visible = FALSE)
    )
  )
) %>% formatStyle(
  c("method1", "method2", "method3", "method4"), 
  valueColumns = 6:9,
  backgroundColor = styleEqual(nY, colcol)
)

字符串


的数据

相关问题