Toluene
Toluene

Reputation: 213

Generate data.frame in Shiny with a n number of vectors using an input

I´m having some trouble to understand why "testTable2" is not working (see code below), while there is no problem if I add the values manually to the data frame. Please have a look and let me know where am I messing up or point me in the right direction. Many thanks!

library(shiny)

ui <- fluidPage(

    # Application title
    titlePanel("test"),

    # Sidebar  
    sidebarLayout(
        sidebarPanel(
            sliderInput("n",
                        "Number",
                        min = 1,
                        max = 10,
                        value = 5)
        ),

        # Show table
        mainPanel(
          tableOutput("testTable1"),
          tableOutput("testTable2")
        )
    )
)

# Define server logic 
server <- function(input, output) {

    #generate some vectors using input$n
    vec1<-reactive({
        rnorm(input$n,mean=0,sd=1)
    })
    vec2<-reactive({
        rnorm(input$n,mean=1,sd=1)
    })
    vec3<-reactive({
        rnorm(input$n,mean=10,sd=0.5)
    })
    vec4<-reactive({
        rnorm(input$n,mean=3,sd=5)
    })
    vec5<-reactive({
        rnorm(input$n,mean=-1,sd=2)
    })
    
    #create a table manually
    output$testTable1<-renderTable({
        data.frame(vec1(),vec2(),vec3(),vec4(),vec5())
    })
    #add vectors to a table using an input
    output$testTable2<-renderTable({
        data.frame(sapply(paste0("vec",1:input$n),get()))
    })
}

# Run the application 
shinyApp(ui = ui, server = server)

Upvotes: 0

Views: 151

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388807

To dynamically access reactive functions you can use -

output$testTable2<-renderTable({
      data.frame(sapply(paste0("vec",1:input$n),function(x) get(x)()))
})

Complete app code -

library(shiny)

ui <- fluidPage(
  
  # Application title
  titlePanel("test"),
  
  # Sidebar  
  sidebarLayout(
    sidebarPanel(
      sliderInput("n",
                  "Number",
                  min = 1,
                  max = 10,
                  value = 5)
    ),
    
    # Show table
    mainPanel(
      tableOutput("testTable1"),
      tableOutput("testTable2")
    )
  )
)

# Define server logic 
server <- function(input, output) {
  
  #generate some vectors using input$n
  vec1<-reactive({
    rnorm(input$n,mean=0,sd=1)
  })
  vec2<-reactive({
    rnorm(input$n,mean=1,sd=1)
  })
  vec3<-reactive({
    rnorm(input$n,mean=10,sd=0.5)
  })
  vec4<-reactive({
    rnorm(input$n,mean=3,sd=5)
  })
  vec5<-reactive({
    rnorm(input$n,mean=-1,sd=2)
  })
  
  #create a table manually
  output$testTable1<-renderTable({
    data.frame(vec1(),vec2(),vec3(),vec4(),vec5())
  })
  #add vectors to a table using an input
  output$testTable2<-renderTable({
      data.frame(sapply(paste0("vec",1:input$n),function(x) get(x)()))
  })
}

# Run the application 
shinyApp(ui = ui, server = server)

Upvotes: 1

Related Questions