Shiny: functional programming

Hi guys. I got a taste for functional programming in shiny, but given my level of expertise I would like to get a bit of feedback on whether or not it is valid way of doing stuff. I wrote a simple function which returns a function that can be used in collapsing time series using tsibble. When plotting longer time series, it is useful to have a function which automatically collapses the data when a longer time series is plotted but provides uncollapsed time series for shorter ones.

library(plotly)
library(dplyr)
library(shiny)
library(shinyWidgets)
library(lubridate)
library(tsibble)

ui = fluidPage(
  dateRangeInput("dr", label = "f", start = today() - 60, end = today()),
  plotlyOutput("plot")
)

server = function(input, output, session){
  
    
  output$plot = renderPlotly({
    get_fct = 
      function(x){
        if(x <= 30){
          function(y){
            ymd(y)
          }
        }else if(x > 30){
          function(y){
            yearmonth(y)
          }
        }
      }
    
    collapsing_function = get_fct(x = as.numeric(input$dr[2] - input$dr[1]))
    
    df = tibble(date = seq(input$dr[1], input$dr[2], by = "days"), value = rnorm(as.numeric(input$dr[2] - input$dr[1]) + 1), key = 1:(as.numeric(input$dr[2] - input$dr[1]) + 1)) #dateRangeInput generates data - think of it as if filtering SQL database using input$dr
    df %>% 
      as_tsibble(index = date, key = key) %>% 
      index_by(Period = collapsing_function(date)) %>% 
      summarise(value = sum(value)) %>% 
      plot_ly(x = ~Period, y = ~value, type = "bar")
  })
}

shinyApp(ui, server)

4 Likes

This post was flagged by the community and is temporarily hidden.

This can be further simplified:

get_fct = 
      function(x){
        if(x <= 30){
          ymd
          }else if(x > 30){
          yearmonth
          }
        }
     
    
    collapsing_function = get_fct(x = as.numeric(input$dr[2] - input$dr[1]))

Hey Bayo. Feel free to post your questions on this forum. I am currently occupied with my projects, but I would gladly help you to solve any arising problems, if I have enough expertise for it.