r - 尝试使用 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)
解决方案
我不确定您要做什么,但这是一个最小的可重现示例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
。
更新
您更新的代码示例存在一些问题:
- 在该
reactive
块中,您正在汇总数据以给出一个数字。基于单个数字绘制直方图是没有意义的。其次,有一个错字:应该mtcars
不是mtcars()
;最后,group_by(cyl = cyl)
这是不必要的,因为您之后不进行任何分组计算(它也应该是group_by(cyl)
)。 - 您实际上根本不需要在
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)
推荐阅读
- r - 重新排列 R 中的相关矩阵以获得 1 的诊断
- performance-testing - 了解 RPS on Locust 摘要结果
- hibernate - 有没有办法在由于 BatchUpdateException 而失败之前跟踪或获取 JPA 完成的批迭代总数?
- python - 找到模式后如何搜索模式?
- android - 如何使用 proguard 将文件保存在 assets 文件夹中?
- matlab - 如何将字符附加到现有的 csv 文件?
- mysql - Drupal 7 从 mysql 数据库恢复不起作用
- javascript - 使用javascript在aspx中回发后保持Div可见或隐藏
- windows-community-toolkit - 用于脚本的 WebView 对象 / Window.External
- r - 如何将日期转换为 FY 半年刊