我想知道如何在一个模块中访问另一个模块的反应函数。如果我在模块中有多个无功功能,我可以在另一个模块中访问它们吗?
所以基本上我如何调用/将一个闪亮模块中的反应函数传递给另一个闪亮模块(从一个模块到另一个模块的反应函数) 感谢
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)
由于
答案 0 :(得分:3)
您需要在模块中使用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)