table command fails with shiny input variable

101 views Asked by At

I'm creating my first shiny app, everything works fantastic when using ggplot2 but using other base R or vcd plots has me stuck. I'd like the user to be able to select a tabling variable and then view a resulting mosaic or association plot. My server code fails at the table command. Things I've already tried are commented out below.

Thanks for the help.

library(shiny)
library(shinydashboard)
library(vcd)

header = dashboardHeader(title = 'Min Reproducible Example')
sidebar = dashboardSidebar()
body = dashboardBody(
  fluidRow(plotOutput('plot'), width=12),
  fluidRow(box(selectInput('factor', 'Select Factor:', c('OS', 'Gender'))))
    )


ui = dashboardPage(header, sidebar, body)

server = function(input, output){
  set.seed(1)
  df = data.frame(Condition = rep(c('A','B','C','D'), each = 300), 
                  Conversion = c(sample(c('Convert','Not-Convert'), 300,      replace = TRUE, prob = c(0.9, 0.1)), 
                             sample(c('Convert','Not-Convert'), 300, replace = TRUE, prob = c(0.7, 0.3)), 
                             sample(c('Convert','Not-Convert'), 300, replace = TRUE, prob = c(0.5, 0.5)),
                             sample(c('Convert','Not-Convert'), 300, replace = TRUE, prob = c(0.2, 0.8))),
                  Gender = sample(c('M','F'), 1200, replace = TRUE),
                  OS = rep(sample(c('Web','iOS','Android'), 1200, replace = TRUE), times = 2))

      #tried this
      #table1 = reactive({
      #  with(df, table(Condition, Conversion, input$factor))

      #})

  output$plot = renderPlot({
    #fails here:
    table1 = with(df, table(Condition, Conversion, input$factor))

    #also tried these
    #table1 = with(df, table(Condition, Conversion,     as.character(isolate(reactiveValuesToList(input$factor)))))
    #also tried table1 = with(df, table(Condition, Conversion, input$factor))
    #also tried table1 = table(df$Condition, df$Conversion, paste0('df$', input$factor))



    #then I want some categorical plots
    assoc(table1, shade=TRUE)
    #or mosaicplot(table1, shade=TRUE)
  })
}


shinyApp(ui, server)
1

There are 1 answers

0
Joe On BEST ANSWER

An easy fix would be to use 'starts_with' from dplyr in a select() statement on your input variable

library('dplyr')

output$plot = renderPlot({

  df <- select(df, Condition, Conversion, tmp_var = starts_with(input$factor))

  table1 = with(df, table(Condition, Conversion, tmp_var))

  mosaicplot(table1, shade=TRUE)

  })
}