'Time series data visualization in R Shiny
I have a sample dataset that I am trying to visualize point data for a selected based of a slider. But I am getting an error with xts which is as follows:
Error in try.xts: must be either xts-coercible or timeBased
How can this error be fixed?
Sample data
Date= c("2014-04-08", "2014-06-04", "2014-04-30",
"2014-05-30", "2014-05-01")
lat = as.numeric(c("45.53814", "45.51076", "45.43560", "45.54332",
"45.52234"))
lon = as.numeric(c("-73.63672", "-73.61029", "-73.60100",
"-73.56000 ", "-73.59022"))
id = as.numeric(c("1", "2", "3", "4", "5"))
Code
# This is a Shiny time series map web application
library(shiny)
library(tidyverse)
library(tidyr)
library(leaflet)
library(xts)
# Create a df from the above columns
df = data.frame(id, lat, lon, Date)
df$Year = lubridate::year(df$Date)
df$Month = lubridate::month(df$Date, label = TRUE, abbr=FALSE)
df$Week = lubridate::week(df$Date)
df$Date = as.Date(df$Date)
ui = fluidPage(
# Title
titlePanel("Time Series Visiualization Map"),
sidebarLayout(
# Define the sidebar
sidebarPanel(
radioButtons(inputId = "Frequency",
label = " Select Timer Series Frequency",
choices = c("Week",
"Month",
"Year"),
selected = "Week",
inline = T),
uiOutput("Time_Series_UI")
),
mainPanel(
leafletOutput("Time_Series_Map")),
))
# Define server logic required
server = function(input, output) {
# Render slider input depending on data frequency
observe({
All_Dates = unique(df$Start_Date)
Filtered_Dates = All_Dates[xts::endpoints(
All_Dates, on = input$Frequency)]
output$Time_Series_UI = renderUI({
sliderInput("Date", "Date:",
min = min(Filtered_Dates),
max = max(Filtered_Dates),
value = min(Filtered_Dates),
step = 1,
timeFormat = "%YYYY-%MM-%DD",
animate = T)
})
})
# Filter data for the date selected
Filtered_Data = reactive({
req(input$Date)
df[df$Date == input$Date]
})
# Create the leaflet map
output$Time_Series_Map = renderLeaflet({
leaflet(df) %>%
addTiles() %>%
setView(lat = 0, lng = 0, zoom = 2)
})
# Create data markers for selected date
observe({
df$id = Filtered_Data()
leafletProxy("Time_Series_Map", data = df) %>%
addCircleMarkers(lng = ~lon, lat = ~lat,
popup = ~id)
})
}
# Run the application
shinyApp(ui = ui, server = server)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
