Shiny - 在用于 ggplot 的反应式 dplyr 表达式中使用来自滑块输入的日期范围

DTY*_*TYK 1 r date ggplot2 shiny dplyr

我正在创建一个闪亮的应用程序,显示各种股票的各种财务指标的趋势。每季度末提供各种股票的财务指标。

我想让我的最终用户能够使用滑块输入来选择他们分析的日期范围。以前关于 SO 的问题涉及为其滑块使用单个值而不是范围(例如这篇文章)。因此,我无法复制解决方案。

以下是我使用的包和模拟数据文件。有 3 列:(a) 日期,(b) 股票,(c) 特定指标的值。

library(shiny)
library(readxl)
library(dplyr)
library(ggplot2)
library(lubridate)

df <- data.frame(Date = c("30/09/2018", "30/06/2018", "31/03/2018", "31/12/2017", "30/09/2017", "30/06/2017",
                      "31/03/2017", "30/09/2018", "30/06/2018", "31/03/2018", "31/12/2017", "30/09/2017", "30/06/2017",
                      "31/03/2017"),
             Stock = c(rep("AAA", 7), rep("BBB", 7)),
             Value = c(5.1, 5.2, 5.6, 5.5, 5.6, 5.7, 5.6, 6.4, 6.9, 6.7, 7.2, 7.2, 7.2, 7.7))

df$Date <- as.Date(df$Date, format = "%d/%m/%Y")
df$Stock <- as.character(df$Stock)
Run Code Online (Sandbox Code Playgroud)

以下是用户界面:

# Define UI for application
ui <- fluidPage(

  # Application title
  titlePanel("Stock Financials Trend"),

  # Sidebar with slider input to select date range
  sidebarLayout(
    sidebarPanel(
      selectInput("Stock_selector",
                  "Stock:",
                  c("AAA", "BBB")),

      # Add a Slider Input to select date range
      sliderInput("Date_range_selector", "Select Date Range",
                  min = 2017,
                  max = 2018,
                  value = c(2017, 2018))
    ),

    # Show a plot of the trend
    mainPanel(
      plotOutput("plot")
    )
  )
)
Run Code Online (Sandbox Code Playgroud)

服务器如下:

server <- function(input, output) {

  filtered_df <- reactive({
    df %>%
      filter(Stock == input$Stock_selector & year(Date) == between(year(Date), input$Date_range_selector[1], input$Date_range_selector[2]))
  })

  output$plot <- renderPlot({
    ggplot(filtered_df(), aes_string(x = "Date", y = "Value")) + geom_line() + geom_point() +
  labs(title = paste(input$Stock_selector, "Trend", sep = " "), y = "Value")
  })    
}

# Run the application 
shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)

我的脚本显示过滤是使用 dplyr 表达式完成的,然后将其分配给一个反应式表达式,以便随后使用 ggplot 进行绘图。

上面的脚本显示了一个空白输出。

我还尝试将numeric函数中 2017 和 2018的值替换为sliderInputyear(as.Date("2017", format = "%d/%m/%Y"))但输出仍然失败。

所需的输出类似于以下内容(假设选择了股票 AAA 并且范围设置为 2018 年到 2018 年):

预期输出

谢谢!

arg*_*t91 7

您需要year(Date) ==在过滤器语句中删除,即将其更改为:

filtered_df <- reactive({
    df %>%
      filter(Stock == input$Stock_selector & between(year(Date), input$Date_range_selector[1], input$Date_range_selector[2]))
  })
Run Code Online (Sandbox Code Playgroud)