如何在另一个闪亮的模块中调用闪亮的模块(从一个模块到另一个模块的反应功能)

sha*_*ary 1 module r shiny

我想知道如何将一个模块中的反应式函数访问到另一个模块。如果我在一个模块中有多个反应性函数,我可以在另一个模块中访问它们吗?

所以基本上我将如何调用/传递一个闪亮模块中的反应函数到另一个闪亮模块(从一个模块到另一个模块的反应函数)谢谢

module1Ui <- function(id) {
  ns <- NS(id)

  wellPanel(selectInput(
    ns("cars"),
    "cars:",
    list(
      "Select" = "",
      "a" = "mazda",
      "b" = "ford"
    )
  ))
}


module1 <- function(input, output, session) {
  dataone <- reactive({
    if (input$cars == "mazda") {
      mtcars$mpg
    }
    else {
      (mtcars$hp)
    }
  })
}
module2 <- function(input, output, session) {
  dataone()
  # here I want dataone from the above module1
  # I tried to use callmodule(module1,_) but then didnt understand what the id would be in this case?
}

library(shiny)

ui <-
  fluidPage(
    sliderInput("slider", "how much cars?", 1, 10, 1, width = "100%"),
    uiOutput("selectors"),
    verbatimTextOutput("datap")
  )

server <- function(input, output, session) {
  for (i in 1:10)
    callModule(module1, i)
  output$selectors <- renderUI({
    lapply(1:input$slider, module1Ui)
  })

  # below  code just to test if I was able to correctly get dataone()      #from module2
  output$datap <- renderPrint(lapply(1:input$slider, function(i) {
    datas <- callModule(module2, i)
    datas()
  }))
}

shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)

谢谢

sho*_*aco 5

您需要return在模块中使用将反应返回给应用程序或调用嵌套模块的模块。在调用层,用于<-分配返回值。然后它可以在调用嵌套模块的层中使用。请参阅工作示例:

module1Ui <- function(id) {
  ns <- NS(id)

  wellPanel(selectInput(ns("cars"), "Select", c("mpg", "hp")))
}


module1 <- function(input, output, session) {
  dataone <- reactive({
    req(!is.null(input$cars))
    return(input$cars)
  })

  # return dataone so that it is visible in the app
  return(dataone)
}
module2 <- function(input, output, session, dataone) {
  # if you want to use dataone() here, you need to do so in a reactive context, e.g. observe, render*, ...
  observeEvent(dataone(), {
    print(dataone())
  })

  # return dataone so that it is visible in the app
  return(dataone)
}

library(shiny)

ui <-
  fluidPage(
    sliderInput("slider", "how much cars?", 1, 10, 1, width = "100%"),
    uiOutput("selectors"),
    verbatimTextOutput("datap")
  )

server <- function(input, output, session) {
  # create a list for all dataone-Vectors
  dataones <- list()
  for (i in 1:10)
    # fill the list with each dataone
    dataones[[i]] <- callModule(module1, i)

  output$selectors <- renderUI({
    lapply(1:input$slider, module1Ui)
  })

  # below  code just to test if I was able to correctly get dataone()
  #from module2
  output$datap <- renderPrint({
    lapply(1:input$slider, function(i) {
      datas <- callModule(module2, i, dataones[[i]])
      return(paste("Input", i, "returned", datas()))
    })
  })
}

shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明