1

I am having problems with reactively passing date-time collapsing functions into index_by function from package tsibble.

index_by takes as an argument a time function (for example week() or month() from lubridate) and collapses the data accordingly.

I want the collapsing to be reactive to user input (specifically selected data-range).

Example: if selected date-range > 60, collapse using week(), if selected date-range > 120, collapse using month().

EDIT: I am specifically refering to using tsibble in the context of server side of shiny module for plotting. Example:

mod_plot = function(input, output, session, df, date_Range){
  output$plot = renderPlotly({
    df() %>%
      index_by(collapse_time = week(.)/month(.)) %>%
      summarise(trace1 = sum(trace1))%>%
      plot_ly(type = 'bar', x = ~collapse_time, y = ~trace1)
  })
}

In order to avoid code duplicity, it would be great to somehow pass date collapsing functions into index_by. Example using tibbletime:

  mod_plot = function(input, output, session, df, date_Range){
      output$plot = renderPlotly({
      #create reactive variable collapse_time based on selected time range
      collapse_time = renderText(if(as.numeric(date_Range$selectdateRange[2] - date_Range$selectdateRange[1]) <= 60){"daily"}
                               else if(as.numeric(date_Range$selectdateRange[2] - date_Range$selectdateRange[1]) < 120){"weekly"}
                               else{"monthly"})
        df() %>%
          collapse_by(collapse_time ) %>%
          group_by(date) %>%
          summarise(trace1 = sum(trace1))%>%
          plot_ly(type = 'bar', x = ~date, y = ~trace1)
      })
    }

This allows for concise and readable pipeline.

Steffen Moritz
  • 7,277
  • 11
  • 36
  • 55
ayasugihada
  • 329
  • 1
  • 2
  • 13
  • I'd probably split the tsibble into two for `date-range > 60` and `date-range > 120` respectively. It doesn't make sense to put `week()` and `month()` into one tsibble. – Earo Wang Aug 13 '19 at 05:33
  • Hi Earo. (sidenote:thanks for the great package!). Should have had mentioned, that it is all about using tsibble inside reactive shiny application. It is a part of the module for plotting barchart. More info in the edited post. – ayasugihada Aug 13 '19 at 07:54

1 Answers1

0

This custom function returns desired collapsing function based on selected date-range.

get_fct =
      function(x){
        if(date_Range$selectdateRange[2] - date_Range$selectdateRange[1] <= 60){
            ymd
        }
        else if(date_Range$selectdateRange[2] - date_Range$selectdateRange[1] < 120){
            yearweek
        }
        else if(date_Range$selectdateRange[2] - date_Range$selectdateRange[1] >= 120){
            yearmonth}
      }


  collapsing_function = get_fct(x = as.numeric(date_Range$selectdateRange[2] - date_Range$selectdateRange[1]))
ayasugihada
  • 329
  • 1
  • 2
  • 13