table 命令失败,输入变量闪亮

table command fails with shiny input variable

我正在创建我的第一个闪亮的应用程序,使用 ggplot2 时一切都很好,但使用其他 base R 或 vcd 图让我卡住了。我希望用户能够 select 制表变量,然后查看生成的镶嵌图或关联图。我的服务器代码在 table 命令中失败。我已经尝试过的事情在下面被注释掉了。

感谢您的帮助。

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)

一个简单的解决方法是在输入变量

的 select() 语句中使用来自 dplyr 的 'starts_with'
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)

  })
}