Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract dyRangeSelector values from dygraph in shiny app

Tags:

r

shiny

dygraphs

I've been using the dygraphs library to put some very nice timeseries plots in a shiny app. I particularly like using the group argument to dygraph in combination with dyRangeSelector to sync the zoom level across multiple dygraphs.

Is there a way to make other shiny outputs reactive to user manipulations of the range selector? Take this example app which shows a simple dygraph and sums the series in a table below:

# app.R
library(shiny)
library(dygraphs)
library(dplyr)

indoConc <- Indometh[Indometh$Subject == 1, c("time", "conc")]

ui <- fluidPage(
  dygraphOutput("plot"),
  tableOutput("table")
)

server <- shinyServer(function(input, output) {

  output$plot <- renderDygraph({
    indoConc %>%
      dygraph %>%
      dyRangeSelector
  })

  output$table <- renderTable({
    indoConc %>%
      filter(time >= min(indoConc$time), time <= max(indoConc$time)) %>%
      summarise(total_conc = sum(conc))
  })
})

shinyApp(ui, server)

I'd like that table to only sum over the time interval currently selected by the user. This means changing the filter line to use something other than those min/max points (which result in no filtration).

How can I extract those two values from the range selector in the appropriate format so I can use them in that filter call, and have the table update reactively as the user moves the sliders?

like image 327
ClaytonJY Avatar asked Oct 04 '16 18:10

ClaytonJY


1 Answers

Since your time variable in the dataframe is a 3 digit variable I would suggest that you convert the datetime object into a character and then select the last 3 digits that you need, and coarse it to a numeric for further use, like so:

rm(list = ls())
library(shiny)
library(dygraphs)
library(dplyr)
library(stringr)

indoConc <- Indometh[Indometh$Subject == 1, c("time", "conc")]
takeLastnvalues <- -3
ui <- fluidPage(dygraphOutput("plot"),tableOutput("table"))

server <- shinyServer(function(input, output,session) {

  values <- reactiveValues()  
  observeEvent(input$plot_date_window,{
    value1 <- input$plot_date_window[[1]]
    value2 <- input$plot_date_window[[2]]
    value1 <- sub("Z", "", value1)
    value2 <- sub("Z", "", value2)
    value1 <- str_sub(value1,takeLastnvalues,-1)
    value2 <- str_sub(value2,takeLastnvalues,-1)
    values$v1 <- as.numeric(value1)
    values$v2 <- as.numeric(value2)
  })

  output$plot <- renderDygraph({
    indoConc %>%
      dygraph %>%
      dyRangeSelector
  })

  output$table <- renderTable({
    indoConc %>%
      filter(time >= min(values$v1), time <= max(values$v2)) %>%
      summarise(total_conc = sum(conc))
  })
})

shinyApp(ui, server)

enter image description here

like image 105
Pork Chop Avatar answered Nov 21 '22 11:11

Pork Chop