这是一个基于您在问题中描述的工作示例。我认为你的方向是正确的。关键是为数据框的子集创建一个反应对象。在我的示例中,它被称为sub_dat。然后我们可以根据sub_dat计算mean和sd,并用textOutput打印出来。
由于您使用的是dplyr,我认为没有必要使用基本 R 子集函数。我们可以使用filter 完成所有子集任务。另一件事是我认为您不需要任何 group_by 操作。但如果你这样做,很容易修改我的示例以包含group_by 操作。
# Load packages
library(tidyverse)
library(lubridate)
library(shiny)
# Create example data frame
dailyprice_gather <- tribble(
~Date, ~price, ~Industry, ~stock,
'29/10/2018', 3, 'Airline', 'A',
'28/10/2018', 4, 'Airline', 'A',
'27/10/2018', 2, 'Airline', 'A',
'29/10/2018', 5, 'Bank', 'B',
'29/10/2018', 3, 'Food', 'C',
'28/10/2018', 4, 'Bank', 'B',
'27/10/2018', 2, 'Bank', 'B',
'27/10/2018', 6, 'Food', 'C')
# Convert to date class
dailyprice_gather <- dailyprice_gather %>% mutate(Date = dmy(Date))
# A vector to show the choices for industry
ind_choices <- sort(unique(dailyprice_gather$Industry))
# A vector to show the choices for the stock
stock_choices <- sort(unique(dailyprice_gather$stock))
# Create the UI
ui <- fluidPage(
# Select the date range
dateRangeInput(inputId = "DateRange", label = "Select Date Range",
start = min(dailyprice_gather$Date),
end = max(dailyprice_gather$Date),
min = min(dailyprice_gather$Date),
max = max(dailyprice_gather$Date)),
# Select the Industry
selectInput(inputId = "Industry", label = "Select the Industry",
choices = ind_choices, selected = ind_choices[1]),
# Select the stock
selectInput(inputId = "Stock", label = "Select the Stock",
choices = stock_choices, selected = stock_choices[1]),
# Show the mean
h3("The Mean of Price"),
textOutput(outputId = "MEAN"),
# Show the standard deviation
h3("The SD of Price"),
textOutput(outputId = "SD")
)
# Create SERVER
server <- function(input, output) {
# # Create a reactive object for subset data frame
sub_dat <- reactive({
dailyprice_gather %>%
filter(Date >= input$DateRange[1],
Date <= input$DateRange[2],
Industry %in% input$Industry,
stock %in% input$Stock)
})
# Calculate the mean and sd based on sub_dat
output$MEAN <- renderText({
as.character(mean(sub_dat()$price))
})
output$SD <- renderText({
as.character(sd(sub_dat()$price))
})
}
# Run the application
shinyApp(ui = ui, server = server)