我想有条件地将单元格颜色更改为红色(例如 PARAMCD==“Param1”和 AVAL < 0). Is it doable using formatstyle() of DT. I dont want to use custom JS since formatstyle will allow me to easier configure whether I want to process server side or client side with server=TRUE or FALSE. Any suggestion ? I tried below code but getting error.
# Load necessary libraries
library(shiny)
library(DT)
# Define UI
ui <- fluidPage(
titlePanel("Shiny Testing"),
sidebarLayout(
sidebarPanel(
selectInput("test1", "Select Test 1", choices = NULL),
selectInput("test2", "Select Test 2", choices = NULL)
),
mainPanel(
DTOutput("olink")
)
)
)
library(dplyr)
library(shiny)
library(DT)
# Define server logic
server <- function(input, output, session) {
data <- data.frame(
USUBJID = rep(1:10, each = 5),
AVISIT = rep(1:5, times = 10),
PARAMCD = rep(paste0("Param", 1:10), each = 5),
AVAL = rnorm(50)
)
unique_paramcd <- setNames(data$PARAMCD, data$PARAMCD)
observe({
updateSelectInput(session, "test1", choices = unique_paramcd)
updateSelectInput(session, "test2", choices = unique_paramcd)
})
# Define a function to preprocess the data and add a new column for background color
preprocessData <- function(data) {
data$BackgroundColor <- ifelse(data$PARAMCD == "Param1" & data$AVAL < 0, "red", "white")
return(data)
}
output$olink <- renderDT({
data <- preprocessData(data)
datatable(data) %>%
formatStyle(
columns = "AVAL",
valueColumns = "BackgroundColor",
backgroundColor = styleEqual(c("white", "red"))
)
})
}
问题是,作为第一个参数,您必须将唯一值的向量传递给要为其分配颜色的
styleEqual
,并且只有作为第二个参数才应该传递颜色。为了清楚起见,我使用布尔值作为条件。此外,我添加了代码来隐藏具有条件的列。
注意:我删除了闪亮的代码以使示例更加简洁并专注于
DT
。
library(DT)
set.seed(123)
data$BackgroundColor <- data$PARAMCD == "Param1" & data$AVAL < 0
datatable(data,
options = list(columnDefs = list(list(visible = FALSE, targets = 5)))
) |>
formatStyle(
columns = "AVAL",
valueColumns = "BackgroundColor",
backgroundColor = styleEqual(
c(FALSE, TRUE),
c("white", "red")
)
)