我使用rpivotTablehtmlwidget,它包裝了優秀的PivotTable.js庫。我想根據單元格的值有條件地格式化數據透視表。Shiny + JS:基於透視值的條件格式化
爲此,我試圖修改here功能。下面是一個最小的閃亮應用與rpivotTable
:
rm(list = ls())
library(shiny)
library(shinydashboard)
library(rpivotTable)
library(dplyr)
#==========================================================
# simulate some data for the pivot table
#==========================================================
df_pivot = data_frame(
factor1 = sample(rep(LETTERS[1:2], 100)),
factor2 = sample(rep(LETTERS[5:6], 100)),
factor3 = sample(rep(LETTERS[19:20], 100)),
value = abs(rnorm(200))
)
#==========================================================
# ui
#==========================================================
pivot_body = dashboardBody({
tags$head(includeScript("pivot.js"))
tags$head(
tags$style(
HTML(
".realGone { background-color: #F08080 !important; }"
)
)
)
rpivotTableOutput(outputId = "pivot_output")
})
pivot_header = dashboardHeader(title = "Some title.")
pivot_sidebar = dashboardSidebar()
pivot_ui = dashboardPage(
header = pivot_header,
sidebar = pivot_sidebar,
body = pivot_body
)
#==========================================================
# server
#==========================================================
pivot_server = shinyServer(function(input, output, session) {
output$pivot_output = renderRpivotTable({
rpivotTable(
data = df_pivot,
rows = "factor1",
cols = "factor2"
)
})
})
#==========================================================
# run the app
#==========================================================
pivot_app = shinyApp(
ui = pivot_ui,
server = pivot_server
)
runApp(pivot_app)
這裏是我的JS功能的適應性 - 基本思想是尋找與類.pvtVal
元素,添加一個類,對他們CSS樣式基於應用在這個班上。
$(document).ready(function(){
var $labels = $('.pvtVal');
console.log("Reached here.");
for (var i=0; i<$labels.length; i++) {
if ($labels[i].innerHTML < 12) {
$('.pvtVal').eq(i).addClass('expired');
} else if ($labels[i].innerHTML > 12 && $labels[i].innerHTML < 14) {
$('.pvtVal').eq(i).addClass('dead');
} else if ($labels[i].innerHTML > 14) {
$('.pvtVal').eq(i).addClass('realGone');
}
}
});
但是,當我檢查在控制檯中的元素,它們不會出現有realGone
類添加。我的猜測是我誤解了$document().ready
的功能。
它應該是'$(document).ready()'? (注意括號的位置) –
@warmoverflow謝謝。已經修復了。但增加的班級仍然沒有出現。它顯示給你嗎? – tchakravarty
@warmoverflow PS。已經改變了JS功能,以防你打算試用它。 – tchakravarty