Time in sliderInput()

Is there any way to have a time (minutes:seconds) as input in shiny a slider input? Note that a simple numeric input (in seconds) could work as long as the labels in the slider are formatted as (%M:%S). Visualizing tens of seconds could be also nice.
Up to now I found no working help online and tried various solutions myself (using hms and clock) but none worked.
Thank you for your help!

A more elegant solution may exist, but one way to do it would be to create a text input slider using the shinyWidgets package. The example shiny app below does three things:

  • Creates time_labels, which is a character vector of all possible time selections from 00:00 - 60:00
  • In the ui section, sets time_labels as the possible choices in sliderTextInput()
  • In the server section, creates a text output showing the selection

Keep in mind, since these are character inputs, the selected string will need to be parsed to obtain the minutes and seconds (this was the purpose of the renderText() section for getting my_minutes and my_seconds).

library(shiny)
library(shinyWidgets)
library(tidyverse)

time_labels = expand.grid(
  minutes = 0:60,
  seconds = 0:59
  ) %>%
  # add leading 0's
  mutate_at(1:2, ~ifelse(nchar(.) == 1, paste0('0', .), .)) %>%
  # create label
  mutate(time_label = paste0(minutes, ':', seconds)) %>%
  arrange(time_label) %>%
  # remove anything over 60:00
  filter(time_label <= '60:00') %>%
  pull(time_label)


ui <- fluidPage(
  
    sliderTextInput("mySliderText", 
                  "Select a time (minutes:seconds)", 
                  choices = time_labels
                  ),

    textOutput('selection')  
)

server <- function(input, output, session) {
  
  output$selection = renderText({
    req(input$mySliderText)
    
    # first 2 characters of selection
    my_minutes = as.numeric(substr(input$mySliderText, 1, 2))
    # last 2 characters of selection
    my_seconds = as.numeric(substr(input$mySliderText, 4, 5))
   
     total_seconds = 60 * my_minutes + my_seconds
    
    out = paste0('You selected ', my_minutes, ' min, ', my_seconds, ' sec (', scales::comma(total_seconds), ' total seconds)')
    
    out
    
  })
  
}

shinyApp(ui, server)

Here is the result:
image

1 Like

That seems to work fine, thank you! I actually need to be able to select times with a precision down to tens of seconds, which means a longer vector. On the other hand, I don't need to go up to 60 min so it's feasible.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.