如何获取Shiny setInputValue以更改下拉菜单选择?

时间:2019-09-05 17:29:16

标签: shiny

这些种类链接会更改species的基础值,但下拉列表不会更改。我该如何解决?

library(shiny)
library(DT)

data(iris)
iris %>% rowwise %>% mutate(Species=as.character(actionLink(paste0('button_',Species), label = Species, onclick = 'Shiny.onInputChange(\"select_button\",  this.id)' ))) -> iris


shinyApp(
  ui <- fluidPage(
    tags$script("
    Shiny.addCustomMessageHandler('set_species', function(value) {
    Shiny.setInputValue('species', value, {priority: 'event'});
    });"),
    selectInput("species",label = "Species",choices=c("setosa","virginica","versicolor")),
    DT::dataTableOutput("data")
  ),

  server <- function(input, output, session) {

    output$data <- DT::renderDataTable({
      DT::datatable(iris[c(1,75,150),], escape = FALSE, selection = 'none')
    })

    observeEvent(input$select_button, {
      selectedspecies <- strsplit(input$select_button, "_")[[1]][2]
      print(selectedspecies)
      session$sendCustomMessage("set_species", selectedspecies)
    })

  }
)

1 个答案:

答案 0 :(得分:1)

下面的代码将在按下链接时更改选择输入。它还将根据所选内容过滤数据集。我们可以使用updateSelectInput来实现此目的,而无需自定义消息。

还要注意,setInputValue不会设置selectInput的值。它是onInputChange的别名。

  

(注意:如果您听说过一个名为Shiny.onInputChange的函数,那只是Shiny.setInputValue的一个更老,更易混淆的名称;后者是在Shiny v1.1中引入的。尽管从未得到正式的文档或支持,Shiny .onInputChange已被广泛使用,我们不太可能很快将其删除,其行为与Shiny.setInputValue相同。)

https://shiny.rstudio.com/articles/communicating-with-js.html

library(shiny)
library(tidyverse)
library(DT)

data(iris)
iris <- iris %>%
  rowwise() %>%
  mutate(Species = as.character(
    actionLink(
      paste0("button_", Species),
      label = Species,
      onclick = 'Shiny.onInputChange(\"select_button\",  this.id);'
    )
  ))

shinyApp(
  ui <- fluidPage(
    selectInput(
      "species",
      label = "Species",
      choices = c("All", "setosa", "virginica", "versicolor")
    ),
    DT::dataTableOutput("data"),
    textOutput("myText")
  ),

  server <- function(input, output, session) {
    output$data <- DT::renderDataTable({
      data <- iris
      if (input$species != "All") {
        data <- data %>%
          filter(grepl(input$species, Species))
      }
      DT::datatable(data, escape = FALSE, selection = "none")
    })

    observeEvent(input$select_button, {
      selectedspecies <- strsplit(input$select_button, "_")[[1]][2]
      print(selectedspecies)
      updateSelectInput(session, "species", selected = selectedspecies)
    })
  }
)