在 Shiny 中,如果所选变量是数字变量,如何输出直方图,如果是分类变量,如何输出条形图?

In Shiny, how do you output a histogram if the selected variable is numeric and a barplot if it is categorical?

在 Shiny 中,如果选择的变量是数字变量,如何输出直方图,如果是分类变量,如何输出条形图?

您必须定义一个逻辑,哪些变量是数字变量,哪些变量是分类变量,然后您可以绘制不同的图:

library(shiny)
library(ggplot2)

ui <- fluidPage(
  selectInput(inputId = "variable",
              label = "Variable",
              choices = colnames(mtcars)),
  h3(""),
  plotOutput("plot")
)

server <- function(input, output, session) {
  output$plot <- renderPlot({
    req(input$variable)
    g <- ggplot(mtcars, aes(x = !!as.symbol(input$variable)))
      if (input$variable %in% c("mpg", "disp", "hp", "drat", "wt", "qsec")) {
        # numeric
        g <- g + geom_histogram()
      } else {
        # categorical
        g <- g + geom_bar()
      }
    
    g
  })
}

shinyApp(ui, server)