2
votes

I have a fully working function in R which takes some input parameters and returns a matrix. I want to build the same on Shiny app. The input parameters of the function should be slider inputs and the output should be dynamic.

I tried using a reactive function for varying inputs.

     names<- c("A", "B", "C", "D", "E")
     ages<- c(25,24,23,22,21)
     salary<- c(60000,32000,37000,15000,15000)
     data<- data.frame(names,ages, salary)
     header<- dashboardHeader(title="Dynamic")

     sidebar<- dashboardSidebar(sidebarMenu(
     id="id",
     sliderInput("age","AGE",min = 0, max = 50, value = "20")
     ))

     body<- dashboardBody(box(
     dataTableOutput("view")
     ))

     ui<- dashboardPage(header, sidebar, body)

     try_function<- function(age){
     to_show<- data %>% filter(ages>age)
     return(to_show) 
     }

    server<- function(input, output, session) {   
      output$view <- renderDataTable({
        reactive({try_function(input$age)
        })    
      })     
    }

    shinyApp(ui, server)

Can any one help on this. Suppose if I have multiple inputs then how this code should vary.

I expect the output to vary as per parameters on shiny app. This doesn't give me any errors but also doesn't show any output on Shiny.

1

1 Answers

2
votes

Generally speaking, we should never use a reactive call inside a render expression. Reactive expressions are generally used when we are interested in a return value or when functions dont have "side effects". Removing the reactive() call, fixes the issue here.

library(shiny)
library(tidyverse)
library(shinydashboard)

names<- c("A", "B", "C", "D", "E")
ages<- c(25,24,23,22,21)
salary<- c(60000,32000,37000,15000,15000)
data<- data.frame(names,ages, salary)
header<- dashboardHeader(title="Dynamic")

sidebar<- dashboardSidebar(sidebarMenu(
  id="id",
  sliderInput("age","AGE",min = 0, max = 50, value = 20)
))

body<- dashboardBody(box(
  dataTableOutput("view")
))

ui<- dashboardPage(header, sidebar, body)

try_function<- function(age){
  to_show<- data %>% filter(ages>age)
  return(to_show) 
}

server<- function(input, output, session) {   

  output$view <- renderDataTable({
    try_function(input$age)
  })     

}

shinyApp(ui, server)