I would like to click on a point in dygraph and get its corresponding date in "%Y-%m-%d %H:%M:%S" format. Here I've reproduced my problem:
library(dygraphs)
library(tidyverse)
library(data.table)
library(shiny)
dates <- seq(as.POSIXct("2021-01-01 05:00:00"), as.POSIXct("2021-01-05 05:00:00"), by = 8*3600)
set.seed(24)
df <- data.table(date = dates,
percentage = round(runif(length(dates), min = 0, max = 1), digits = 2)
)
ui <- fluidPage(
fluidRow(
column(width = 12,
dygraphOutput("dygraph")
)
),
fluidRow(
verbatimTextOutput("click")
)
)
server <- function(input, output){
output$dygraph <- renderDygraph({
dygraph(df)
})
output$click <- renderPrint({
input$dygraph_click$x
})
}
shinyApp(ui = ui, server = server)
Here is how the output looks like:
My problem is that it doesn't give me the right format. I tried to use the format function, but it did not work. I used the following line inside my renderprint:
format(as.POSIXct(input$dygraph_click$x), "%Y-%m-%d %H:%M:%S")
And here is the output:
It does not show the hour:minute:second properly.
Does anyone know how I can print out the POSIXct format of a date upon clicking on its corresponding point? I would appreciate any help.
You can use lubridate::ymd_hms
to convert input$dygraph_click$x
in POSIXct
format and use format
to display the output.
output$click <- renderPrint({
format(lubridate::ymd_hms(input$dygraph_click$x, tz = Sys.timezone()))
})
Complete code -
library(dygraphs)
library(tidyverse)
library(data.table)
library(shiny)
dates <- seq(as.POSIXct("2021-01-01 05:00:00"),
as.POSIXct("2021-01-05 05:00:00"), by = 8*3600)
set.seed(24)
df <- data.table(date = dates,
percentage = round(runif(length(dates), min = 0, max = 1), digits = 2)
)
ui <- fluidPage(
fluidRow(
column(width = 12,
dygraphOutput("dygraph")
)
),
fluidRow(
verbatimTextOutput("click")
)
)
server <- function(input, output){
output$dygraph <- renderDygraph({
dygraph(df)
})
output$click <- renderPrint({
format(lubridate::ymd_hms(input$dygraph_click$x, tz = Sys.timezone()))
})
}
shinyApp(ui = ui, server = server)