【问题标题】:Shiny - Using Date range from sliderInput in a reactive dplyr expression used for a ggplotShiny - 在用于 ggplot 的反应性 dplyr 表达式中使用来自 sliderInput 的日期范围
【发布时间】:2019-04-26 15:37:33
【问题描述】:

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

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

以下是我正在使用的包和模拟数据文件。共有 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)

以下是用户界面:

# 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")
    )
  )
)

服务器如下:

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)

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

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

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

所需的输出如下所示(假设选择 Stock AAA 并且范围设置为 2018 到 2018):

谢谢!

【问题讨论】:

    标签: r date ggplot2 shiny dplyr


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-13
      • 1970-01-01
      • 2017-10-06
      • 2017-08-06
      • 2016-06-22
      • 2018-06-21
      相关资源
      最近更新 更多