问题
There are many shiny questions on SO asking how to use an input value in UI. The general answer is to use the updateSelect-family or to use renderUI.
I understand that it is basically not possible to access values from the input list (input$...) in the UI, since the input list is only passed to the server and therefore not existent in the UI environment.
What I do not get my head around is, that there are functions such as conditionalPanel which access the input list in javascript and use it to render UI output.
Since those functions actually use the input list in javascript, I wonder whether it is possible to build some shiny function (lets name it js()) which passes the javascript input list back to R and make it accessible in the UI.
It would make creating UIs much easier.
I tried to look deeper into the conditionalPanel function to better understand how the javascript environment is accessed, but the condition argument is passed to a div() attribute called `data-display-if`. From here on I don't know how to dig deeper into the function.
conditionalPanel <- function(condition, ..., ns = NS(NULL)) {
div(`data-display-if`=condition, `data-ns-prefix`=ns(""), ...)
}
Finally I provide a code example of a functional shiny dashboard. I commented out two statements: one which will not work, and one with a fictional function js() that accesses a input value in javascript and passes it to R. It would be great to have such a function in the future.
library("shiny")
library("data.table")
# Generate data
testDT <- data.table(a1 = c(rep("group1",4),rep("group2",4),rep("group3",4)),
a2 = rep(c("red","blue","green"),4),
x1 = c(5,6,7,3,4,5,2,3,4,2,1,7),
x2 = c(1,2,3,2,3,2,1,4,6,7,3,4),
x3 = c(12,43,64,34,93,16,32,74,84,89,45,67)
)
shinyApp(
ui = fluidPage( # user interface
sidebarLayout( # layout with Sidebar
sidebarPanel( # input sidebarPanel
selectInput(inputId = "subset", label = "Choose group",
choices = c("Group 1" = "group1",
"Group 2" = "group2",
"Group 3" = "group3"),
selected = "group1"),
conditionalPanel(
condition = "input.subset == 'group3'", # input value can be access in javascript
sliderInput(inputId = "range x3", label = "Choose range for x3",
min = 0,
max = max(testDT$x3),
# max = max(testDT[a1 == input$subset]$x3), not possible since input list not available in UI
# max = max(testDT[a1 == js('input.subset')]$x3), a function like js() would be great
c(0,max(testDT$x3)),
step = 1))
), # closes sidebarPanel
mainPanel( # Output in mainPabel
tableOutput("table")
) # closes mainPanel
) # closes sidebarLayout
), # closes fluidPage
server = function(input, output) {
react_testDT <- reactive({
testDT[a1 == input$subset,.(x1_mean = mean(x1),
x2_mean = mean(x2),
x3_mean = mean(x3))]
})
output$table <- renderTable({
react_testDT()
})
}
)
来源:https://stackoverflow.com/questions/57096471/access-javascript-objects-from-r-in-shiny-dashboard