Returning a List of Reactive Expressions

683 views
Skip to first unread message

marfaj

unread,
Mar 9, 2017, 4:51:40 PM3/9/17
to Shiny - Web Framework for R
Hello,

In the modules article (https://shiny.rstudio.com/articles/modules.html) it was mentioned that:

"If a module needs to use a reactive expression, take the reactive expression as a function parameter. If a module wants to return reactive expressions to the calling app, then return a list of reactive expressions from the function."


Can you please give me a short example of how can I return a list of reactive expressions and how can I call a specific expression out of that list?

Thank you.

marfaj

unread,
Mar 9, 2017, 4:56:45 PM3/9/17
to Shiny - Web Framework for R

marfaj

unread,
Mar 9, 2017, 6:05:18 PM3/9/17
to Shiny - Web Framework for R
So, I followed Joe's suggestion. I get an error (attempt to apply non-function)..

Could you please let me know what am I doing wrong?



library(shiny)
mod1UI <- function(id){
  ns <- NS(id)
  textInput(ns("txt"), "Enter Your Text", "Default")
}


mod1 <- function(input, output, session){
  exp1 <- reactive({
    h2(paste(input$txt, "exp1"))
  })
  exp2 <- reactive({
    h2(paste(input$txt, "exp2"))
  })
  return(list(exp1, exp2))
}


mod2UI <- function(id){
  ns <- NS(id)
  tagList(
    uiOutput(ns("txtOut"))
  )
}
mod2 <- function(input, output, session, mod1Result){
  output$txtOut <- renderUI(
    tagList(
      mod1Result$exp1(),
      mod1Result$exp2()
    )
  )
}


ui <- fluidPage(
  fluidRow(
    column(12,
           tagList(
             mod1UI("myMod1"),
             mod2UI("myMod2")
           )
    )
  )
)

server <- function(input, output) {
  mod1Result <- callModule(mod1, "myMod1")
  callModule(mod2, "myMod2", mod1Result)
}

shinyApp(ui = ui, server = server)

Joe Cheng

unread,
Mar 9, 2017, 6:36:31 PM3/9/17
to marfaj, Shiny - Web Framework for R
If you make a list like this (no names):

list(exp1, exp2)

then you'd need to access the elements using positions, i.e. result[[1]] and result[[2]].

If you want to access them like result$exp1 and result$exp2 then form the list like this:

list(exp1=exp1, exp2=exp2)

--
You received this message because you are subscribed to the Google Groups "Shiny - Web Framework for R" group.
To unsubscribe from this group and stop receiving emails from it, send an email to shiny-discus...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/shiny-discuss/fee890dd-ea16-4447-a35e-b2304445a92d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

marfaj

unread,
Mar 10, 2017, 4:05:36 PM3/10/17
to Shiny - Web Framework for R, ala...@gmail.com
Thank you. That was it.
Reply all
Reply to author
Forward
0 new messages