pass object generated in server back to ui in shiny

Viewed 1039

I need to create an object (or variable( in my server part and pass back into ui checkboxGroupInput. My file is a little complicated. Here I just use diamonds data to illustrate what I'm trying to do, although what the app is doing is meaningless. I created a df, a subset of diamonds dataset. I'm trying to pass it back to the ui checkboxGroupInput, so that I can select what columns to show. My question is how do I pass df back to ui? thanks in advance.

Here is my app.r:

library(shiny)
library(ggplot2)
library(DT)

ui <- fluidPage(
    sidebarLayout(
        sidebarPanel(
            selectInput("nrow", label = h3("number of rows"), 
                        choices = list(5, 10, 20), 
                        selected = 5),
            checkboxGroupInput("show_vars", "Columns in diamonds to show:",
                                   names(df), selected = names(df))
        ),
        mainPanel(
            DT::dataTableOutput("mytable1")
            )
        )
    )


server <- function(input, output) {

    # choose rows to display
    df = diamonds[sample(nrow(diamonds), input$nrow), ]

    output$mytable1 <- DT::renderDataTable({
        DT::datatable(df[, input$show_vars, drop = FALSE])
    })

}

shinyApp(ui, server)

Error message:

Warning: Error in .getReactiveEnvironment()$currentContext: Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)
1 Answers
Related