【问题标题】:Passing a reactive dataset and function from parent app to module in Shiny将反应式数据集和函数从父应用程序传递到 Shiny 中的模块
【发布时间】:2018-12-18 02:47:10
【问题描述】:

我正在努力将反应式数据集和函数传递给闪亮的模块的工作流程。我对下面的意思做了一个简单的版本;该应用程序只是打印每个 cyl 值的平均 mpg。

library(shiny)

# Module 
textToolUI <- function(id){
  ns <- NS(id)
  textOutput(ns("text"))
} 

textTool <- function(input, output, session, value){
  output$text <- renderText({paste(value)})
}



# App
ui <- basicPage(
  selectInput("carbSelect", "Carburetor Selector", choices = c(1,2,3,4)),
  textToolUI("text1")
)

server <- function(input, output, session){
  data <- reactive(filter(mtcars, carb == input$carbSelect))
  myfunc <- function(x){return(mean(x))}

  callModule(textTool, "text1", value = myfunc(data$mpg))  # This throws up the "object of type closure not subsettable" error
                                                           # Using data()$mpg means it is not reactive
}

shinyApp(ui = ui, server = server) 

问题的出现是因为数据集和函数 (myfunc) 都需要位于模块之外。在我的实际应用中,使用了多个不同的数据集和函数。

我认为这里的问题是函数是在反应数据集之前评估的,因此我需要不同的工作流程,但我想不出合适的替代方案。

【问题讨论】:

  • 值需要是反应性的,看看我在这个答案中遇到的一个非常相似的问题:stackoverflow.com/questions/36695577/… - 在你的情况下,我认为myfunc() 需要在模块中,data作为值传入(没有参数,例如不是data()) - 它需要是一个反应对象。

标签: r function module shiny reactive


【解决方案1】:

模块只需要传递一个响应式对象,没有参数。

下面的例子将函数移动到模块中,并将其转换为表格而不是文本,因为mean(mtcars) 正在输出 NA

library(shiny)

myfunc <- function(x){colMeans(x)}

myfunc2 <- function(x){colSums(x)}

# Module 
textToolUI <- function(id){
  ns <- NS(id)
  tableOutput(ns("text"))
} 

textTool <- function(input, output, session, value, f){

  output$text <- renderTable({
    req(value())
    paste(f(value()))
    })
}



# App
ui <- basicPage(
  selectInput("carbSelect", "Carburetor Selector", choices = c(1,2,3,4)),
  p("myfunc1 - colMeans"),
  textToolUI("text1"),
  p("myfunc2 - colSums"),
  textToolUI("text2")
)

server <- function(input, output, session){
  data <- reactive(dplyr::filter(mtcars, carb == input$carbSelect))

  callModule(textTool, "text1", value = data, f = myfunc)

  callModule(textTool, "text2", value = data, f = myfunc2)
  # Using data()$mpg means it is not reactive
}

shinyApp(ui = ui, server = server) 

【讨论】:

  • 非常感谢,我想我将把函数本身作为参数传递 - 干杯!
猜你喜欢
  • 2016-08-10
  • 1970-01-01
  • 1970-01-01
  • 2019-12-02
  • 1970-01-01
  • 2013-05-26
  • 2019-04-27
  • 2014-09-20
  • 2016-11-30
相关资源
最近更新 更多