首页 > 解决方案 > 使用复选框从 Shiny 中的 R DataTable 中选择特定数据并创建直方图

问题描述

我在 Shiny 中创建了一个带有 DT 的数据表,如下所示:

在此处输入图像描述

我想在满足某些属性(例如 Mfr=Mitsubish、Joint=1 等)的侧面板上选择带有复选框的数据,然后实时更新 deg/s 直方图以查看。

我已经阅读了我可以在网上找到的材料,但我不知道如何做到这一点。有没有人有任何提示?

标签: rshiny

解决方案


@guero64 这是我的一个例子,我相信它有你正在寻找的例子。我希望这是有帮助的。它基于diamonds数据集,并有几个checkbox过滤器可以应用于数据。

library(shiny)
library(DT)
library(tidyverse)

ui <- shinyUI(pageWithSidebar(

  headerPanel("Example"),

  sidebarPanel(
    checkboxInput("cb_cut", "Cut (Ideal)", FALSE),
    checkboxInput("cb_color", "Color (I)", FALSE)
  ),

  mainPanel(
    DT::dataTableOutput("data_table"),
    plotOutput("data_plot")
  )
))


server <- shinyServer(function(input, output) {

  filtered_data <- reactive({
    dat <- diamonds
    if (input$cb_cut) { dat <- dat %>% filter(dat$cut %in% "Ideal") }
    if (input$cb_color) { dat <- dat %>% filter(dat$color %in% "I") }
    dat
  })

  output$data_table <- DT::renderDataTable({
    filtered_data()
  })

  output$data_plot <- renderPlot({
    hist(filtered_data()$price, main = "Distribution of Price", ylab = "Price")
  })
})

shinyApp(ui = ui, server = server)

推荐阅读