Вот рабочий пример, основанный на том, что вы описали в своем вопросе. Я думаю, что вы в правильном направлении. Ключ заключается в создании реактивного объекта для подмножества фрейма данных. В моем примере это называется sub_dat
. Затем мы можем вычислить mean
и sd
на основе sub_dat
и вывести его с помощью 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)