search bar module in R shiny how to return results

半城伤御伤魂 提交于 2020-12-15 07:54:12

问题


I'm trying to make a shiny module that will alter a datatable based on a custom searchbar.

I managed to make an app that will print the results of a searchbar search into R-Studio console, but, how do I return the results from the module and update the reactive data storage?

Here is an example app, I want to return what is printed to update the reactive:


myModuleUI <- function(id) {
  ns <- NS(id)
  tagList(
    fluidRow(
      column(width=2, 
          textInput(ns("searchField"), "Search"),
          dataTableOutput("table")
      )
    )
  )
}
myModule <- function(input, output, session, df) {
  observeEvent(input$searchField, {
    if(!is.null(input$searchField)){
      print(
        df %>% filter_at(vars(names(df)), any_vars(str_detect(as.character(.), input$searchField)))
      )
    }
  })
}
# Use the module in an application
ui <- fluidPage(
  myModuleUI("myModule1")
)
server <- function(input, output, session) {
  out <- reactiveValues(
    df = data.frame(
      company = c('a', 'b', 'c', 'd'),
      bond = c(0.2, 1, 0.3, 0),
      equity = c(0.7, 0, 0.5, 1),
      cash = c(0.1, 0, 0.2, 0),
      stringsAsFactors = FALSE
    )
  )
  callModule(myModule, "myModule1", df = out$df)
  output$table <- DT::renderDataTable({
    m <- datatable(
      out$df,
      options = list(dom = 'tip')
    )
  })
}
shinyApp(ui, server)

回答1:


You have to use ns() on datatableOutput outputId too, so you can use it within the module:

myModuleUI <- function(id) {
  ns <- NS(id)
  tagList(
    fluidRow(
      column(width=2, 
             textInput(ns("searchField"), "Search"),
             dataTableOutput(ns("table"))
      )
    )
  )
}
myModule <- function(input, output, session, df) {
  output$table <- DT::renderDataTable({
    datatable(
      if(!is.null(input$searchField)){
          df %>% filter_at(vars(names(df)), any_vars(str_detect(as.character(.), input$searchField)))
      } else df,
      options = list(dom = 'tip')
    )
  })
}
# Use the module in an application
ui <- fluidPage(
  myModuleUI("myModule1")
)
server <- function(input, output, session) {
  out <- reactiveValues(
    df = data.frame(
      company = c('a', 'b', 'c', 'd'),
      bond = c(0.2, 1, 0.3, 0),
      equity = c(0.7, 0, 0.5, 1),
      cash = c(0.1, 0, 0.2, 0),
      stringsAsFactors = FALSE
    )
  )
  callModule(myModule, "myModule1", df = out$df)
}
shinyApp(ui, server)


来源:https://stackoverflow.com/questions/64812459/search-bar-module-in-r-shiny-how-to-return-results

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!