我需要用以下规则有条件地给‘Weight’列的背景上色:非负值是绿色的,负值是红色的,但如果没有正值,那么0也应该是红色.我try 了多种方法,但在我看来,条件formatStyle
不起作用,至少在这种形式下是这样的:
ui <- fluidPage(
DT::dataTableOutput("weight_df")
)
server <- function(input, output, session){
df <- data.frame(weight = rep(1, 3))
rv <- reactiveValues(weight_df = df)
output$weight_df <- renderDataTable({
DT::datatable(
data = df,
caption = htmltools::tags$caption("Weight table"),
editable = list(target = "column"),
) %>%
formatStyle(
"weight",
fontWeight = "bold",
backgroundColor = `if`(
all(df[["weight"]] <= 0),
"orangered",
styleInterval(-10^(-32), c("orangered", "limegreen"))
)
)
})
table_proxy <- DT::dataTableProxy("weight_df")
observeEvent(input$weight_df_cell_edit, {
info <- input$weight_df_cell_edit
new_weights <- info[["value"]]
is_numeric <- checkmate::testNumeric(
x = new_weights,
finite = TRUE,
any.missing = FALSE
)
if(is_numeric)
rv$weight_df[["weight"]][info[["row"]]] <- info[["value"]]
DT::replaceData(table_proxy, rv$weight_df)
})
}
shinyApp(ui, server)
注:无需再次渲染表格.如果所有权重都为0,我可以使其再次渲染.