首页 > 解决方案 > 尝试使用 SelectInput 从数据框中求和

问题描述

重新提出我的问题,我正在尝试使用 selectinput = c("col_1","col_2","col_3","col_4","col_5") 反应性地合成数据帧

我的数据框看起来像这样
Date 。商店 ID 。销售量 。库存 。ETC

我需要能够将同一商店中的所有数据与不同的用户选择的列相加。

以 mtcars 数据框为例,我的目标是有一个这样的表

SelectInput = disp
cyl - disp
4 - sum(每 4 个气缸显示)
6 - sum(每 6 个气缸显示)
8 - sum(每 8 个气缸显示)

选择输入 = qsec
cyl 。qsec
4 . 总和(每 4 个气缸 qsec)
6 。总和(每 6 个气缸 qsec)
8 。总和(每 8 个气缸 qsec)

library(shiny)

图书馆(tidyverse)

ui <- bootstrapPage(
  selectInput(
    "col",
    "Column",
    colnames(mtcars),
    selected = "mpg"),
  plotOutput("histCentile", height = 200)
)

server <- function(input, output) {
  data <- reactive({
    mtcars() %>%
      group_by(cyl = cyl) %>%
      pull(input$col) %>%
      sum()
  })

  output$histCentile <- renderPlot({
    hist(data()$[[input$col]],
         main = "Graph",
         xlab = "Units",
         xlim = range(data()$[[input$col]]),
         col = '#00DD00',
         border = 'white')
  })
}

# Run the application
shinyApp(ui = ui, server = server)

标签: rshiny

解决方案


我不确定您要做什么,但这是一个最小的可重现示例reactive,用于根据selectInput变量过滤数据。

library(shiny)
library(tidyverse)

ui <- bootstrapPage(
    selectInput(
        "col",
        "Column",
        colnames(mtcars),
        selected = "mpg"),
    textOutput("selected_col")
)

server <- function(input, output) {
    data <- reactive({
        mtcars %>% pull(input$col) %>% sum()
    })

    output$selected_col <- renderText({
        sprintf("The sum of column %s is %f", input$col, data())
    })
}

# Run the application
shinyApp(ui = ui, server = server)

说明:在data我们input$col根据selectInput选择对值进行求和。data因此是一个反应值,我们在 中显示output$selected_col


更新

您更新的代码示例存在一些问题:

  1. 在该reactive块中,您正在汇总数据以给出一个数字。基于单个数字绘制直方图是没有意义的。其次,有一个错字:应该mtcars不是mtcars();最后,group_by(cyl = cyl)这是不必要的,因为您之后不进行任何分组计算(它也应该是group_by(cyl))。
  2. 您实际上根本不需要在reactive这里设置块,因为您可以renderPlot直接进行过滤,但我想这是个人喜好问题。

以下根据所选列动态更新直方图selectInput

library(shiny)
library(tidyverse)

ui <- bootstrapPage(
    selectInput(
        "col", 
        "Column", 
        colnames(mtcars),
        selected = "mpg"),
    plotOutput("histo")
)

server <- function(input, output) {
    data <- reactive({
        mtcars %>% pull(input$col)
    })

    output$histo <- renderPlot({
        hist(data())
    })
}

# Run the application 
shinyApp(ui = ui, server = server)

推荐阅读