I am building a Shiny app and have to extract year from date column to create a slider with years. I have a column called date in format YYYY MM DD , trying to extract only the year in the filter part, but it doesn't work as expected. I am stuck at the following code:
server <- function(input, output){
data <- reactive({
ufo %>%
filter(date >= format(as.Date(input$years[1],"%Y")),
date <= format(as.Date(input$years[2], "%Y")))
})
The error I get is:
Problem with filter() input..1.
[34mℹ[39m Input..1 is date >= format(as.Date(input$years[1], "%Y")).
[31mx[39m character string is not in a standard unambiguous format
How can I extract only the year for my filter?
Welcome to stackoverflow, it is always important to ask with a minimal reproducible example of your data, that way we can help you faster.
To do so, you can simulate one or share a fragment of yours.
Here one with what I think you have
library(shiny)
library(dplyr)
library(lubridate)
# Creating a minimal reproducible example of the data
set.seed(123)
ufo <- data.frame(
date = sample(seq(as.Date('2010-01-01'), as.Date('2022-01-01'), by = 'day'), 20),
ufo = sample(1:15, 20, replace = TRUE)
) %>%
arrange(date)
#> date ufo
#> 1 2011-06-10 11
#> 2 2012-08-10 9
#> 3 2012-10-13 10
#> 4 2013-02-15 15
#> 5 2013-12-20 5
#> 6 2014-06-15 7
#> 7 2014-11-25 7
#> 8 2015-01-16 12
#> 9 2015-07-06 7
#> 10 2016-02-05 1
#> 11 2016-09-28 4
#> 12 2016-11-15 14
#> 13 2017-01-10 12
#> 14 2017-07-19 9
#> 15 2017-11-27 11
#> 16 2018-03-05 5
#> 17 2019-03-25 10
#> 18 2019-06-08 13
#> 19 2021-09-30 7
#> 20 2021-10-16 5
Now that we have the data, let's move to the shiny part. It is good as well to include the minimal elements of your app, in this case I put a slider input the server using it.
The problem with your original code is that format()
returns a character and you are comparing that with a date, which do not make sence. It is a better approach to extract the year of your date as numeric using lubridate::year()
and compare that with the slider input values.
# User interface
ui <- fluidPage(
sliderInput('year', 'Year', min = 2010, max = 2022,
step = 1, value = c(2015, 2020), sep = ''),
dataTableOutput('table')
)
server <- function(input, output, session) {
data <- reactive({
ufo %>%
filter(year(date) >= input$year[1], year(date) <= input$year[2])
})
output$table <- renderDataTable({
data()
})
}
Created on 2022-02-14 by the reprex package (v2.0.1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.