Search code examples
rparsingservershiny

Shiny R: call to a server output using a function


I am new in R and Shiny and just started to learn developing/coding. I am trying to use a function to call an output object in the server part. My goal is to use the function many times by passing different inputs. The server output should look like this (very much simplified):

output$Euro <- DT::renderDT(
  NV_Euro()
)

And the function to parse the output looks like this (the input EuroTab below is a data frame):

server_Output <- function(EuroTab){                   
                    output$Euro <- DT::renderDT(
                      EuroTab
                 )

So that i can use the function to parse the output object in the server:

server <- function(input, output, session) {    
          server_Output('NV_Euro')
}

To get:

server <- function(input, output, session) {    
              output$Euro <- DT::renderDT(
                              NV_Euro()
                             )
}

But this doesn't work. Would be grateful if anyone could help :-)


Solution

  • It's possible, but your output always needs unique IDs. If you take this into account, you can create something like this:

    library(shiny)
    
    ui <- fluidPage(
      
      DT::DTOutput("mytable1"),
      DT::DTOutput("mytable2")
      
    )
    
    server <- function(input, output, session) {
      
      #Your function
      myfunction <- function(data, name) {
        
        output[[name]] <- DT::renderDT(
          data
        )
        
      }
      
      #Data Table 1 Output
      myfunction(iris, "mytable1")
      
      #Data Table 2 Output
      myfunction(mtcars, "mytable2")
      
    }
    
    shinyApp(ui, server)
    

    Edit

    Yes, it is possible to use reactives. Note that I pass the unevaluated reactive to the function and only in the function itself evaluate it (by adding the brackets):

    library(shiny)
    
    ui <- fluidPage(
      numericInput("num_row", "max. # of rows",
                   value = min(c(nrow(mtcars), nrow(iris))),
                   max = min(c(nrow(mtcars), nrow(iris)))),
      DT::DTOutput("mytable1"),
      DT::DTOutput("mytable2")
      
    )
    
    server <- function(input, output, session) {
      
      #Your function
      myfunction <- function(data_input, name) {
        
        output[[name]] <- DT::renderDT(
          data_input()
        )
        
      }
      
      my_data_1 <- reactive({
        iris[seq_len(input$num_row), ]
      })
      
      #Data Table 1 Output
      myfunction(my_data_1, "mytable1")
      
      my_data_2 <- reactive({
        mtcars[seq_len(input$num_row), ]
      })
      
      #Data Table 2 Output
      myfunction(my_data_2, "mytable2")
      
    }
    
    shinyApp(ui, server)