Binding a ggvis object to Shiny prevented by unitinitalized variables


#1

Hello all,

I am struggling to create a simple Shiny application. It should do the following: select a column from a data frame on the server and make a bar chart of the values in the selected column. The following code does precisely that and runs fine:

Code for the UI:

library(shiny)
library(ggvis)

shinyUI(fluidPage(
  
  sidebarLayout(
    sidebarPanel(
      
      # Create boxes to select dataframe column
      # uiOutput("selected_column")
      selectInput("selected_column", label = "x", choices = c("column_A", "column_B"))
    ),
    
    # Show plot
    mainPanel(
      ggvisOutput("bar_plot"),
      uiOutput("text")
    )
  )
))

Code for the server:

library(shiny)
library(ggvis)
library(magrittr)

# Generate dataframe
x = sample( c("A", "B", "C", "D"), 10, replace = TRUE)
y = sample( c("Q", "R", "S", "T"), 10, replace = TRUE)
df = data.frame( "column_A"  = x, "column_B" = y)

shinyServer(function(input, output) {
  
  # Create drop-downs for UI
  output$selected_column = renderUI({
    selectInput("selected_column", label = "x", choices = names(df))
  })
  
  # Create data points
  df_plot = reactive({
    
    validate(need( input$selected_column != "", "Please select column"))
    
    df_temp = df[, input$selected_column] %>% as.data.frame()
    colnames(df_temp) = "x"
    df_temp
  })
  
  plot = tryCatch(
    df_plot %>%  ggvis( ~ x) %>% layer_bars(),
    error = function(e){
      cat( file = stderr(), "Error in plot: ", as.character(e), "\n")
    }
  )
  
  tryCatch({
    plot %>% bind_shiny("bar_plot")
    },
    error = function(e){
      cat( file = stderr(), "Error in bind: ", as.character(e), "\n")
    }
  )
  output$text = tryCatch(
    renderText(input$selected_column),
    error = function(e){
      cat( file = stderr(), "Error in output text: ", as.character(e), "\n")
    }
  )
})

Note that the lines

  output$selected_column = renderUI({
    selectInput("selected_column", label = "x", choices = names(df))
  })

serve no purpose because the statement uiOutput("selected_column") has been commented out in the UI code.

If we change this and use the select-box created at the server:

      # Create boxes to select dataframe column
      uiOutput("selected_column")
      # selectInput("selected_column", label = "x", choices = c("column_A", "column_B"))

the app no longer works. I.e., it will display the select box and the selected column via uiOutput("text") but it will not display the plot. The console shows an error Error in plot: Error: Please select column, showing the validate statement has thrown an exception because input$selected_column was not yet initialized.

How do I get around this? Any help is appreciated.