在DataTable输出中实现ifElse(或if_Else),以有条件地更改反应式表格的背景颜色(闪亮和r) [英] Implementing ifelse (or if_else) in datatable output to conditionally change the background color of a reactive table (shiny and r)
本文介绍了在DataTable输出中实现ifElse(或if_Else),以有条件地更改反应式表格的背景颜色(闪亮和r)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试实现这些代码[1],[2]以使用datatable
中的backgroundcolor
参数有条件地更改bG颜色ifresult_post > result_pre
。然而,发生了一些事情,我想有人能够修复这个代码,它部分模仿了原始代码(它使用了反应值)。
目标是
library(shiny)
library(tidyverse)
library(DT)
table_math <- data.frame(age = c(5,10), test = "math", result_pre = rnorm(100,10,2), result_post = rnorm(100,11,1))
ui <- fluidPage(
sidebarLayout(
sidebarPanel( ),
mainPanel(dataTableOutput("main_results"))
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
#backend
table_with_results <- reactive({
datatable(
table_math %>%
select(result_post, result_pre)
,
#format datatable
options = list(
dom = 't',
pageLength = 200
),
rownames = FALSE) %>%
formatStyle(columns = "result_pre",
backgroundColor = styleInterval( 1, #here is the goal: instead of 1 if result_post > result_pre
c("red","green")))
})
#real output
output$main_results <- renderDataTable(
table_with_results()
)
}
# Run the application
shinyApp(ui = ui, server = server)
推荐答案
好的,在搜索了一个Java脚本函数后,我终于找到了这个解决方案here和here和here。这取决于rowCallback
函数。请随意使用它。最终输出为:
library(shiny)
library(tidyverse)
library(DT)
#>
#> Attaching package: 'DT'
#> The following objects are masked from 'package:shiny':
#>
#> dataTableOutput, renderDataTable
table_math <- data.frame(age = c(5,10), test = "math", result_pre = rnorm(100,10,2), result_post = rnorm(100,11,1))
rowCallback <- c(
"function( row, data, index ) {
if (data[0] > data[1]) { //index 0 = result_post and index 1 = result pre
$(row).find('td:eq(0)').css('background-color', '#ffa');
};
}"
)
ui <- fluidPage(
sidebarLayout(
sidebarPanel( ),
mainPanel(dataTableOutput("main_results"))
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
#backend
table_with_results <- reactive({
datatable(
table_math %>%
select(result_post, result_pre)
,
#format datatable
options = list(
rowCallback = JS(rowCallback),
dom = 't',
pageLength = 200
),
rownames = FALSE)
})
#real output
output$main_results <- renderDataTable(
table_with_results()
)
}
# Run the application
shinyApp(ui = ui, server = server)
#> PhantomJS not found. You can install it with webshot::install_phantomjs(). If it is installed, please make sure the phantomjs executable can be found via the PATH variable.
Static R Markdown文档中不支持闪亮的应用程序
创建于2022-02-02reprex package(2.0.1版)
这篇关于在DataTable输出中实现ifElse(或if_Else),以有条件地更改反应式表格的背景颜色(闪亮和r)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文