I am trying to make a shiny app that first imports data in the first tab and plots a ggplot based on the imported data and the user-chosen data range in the second tab. The below code doesn't give me an error, but my plot is not getting updated as I change my date range.
library(shiny)
library(ggplot2)
library(dplyr)
df <- data.frame("date" = c("2020-01-01", "2020-01-01", "2020-01-02", "2020-01-02"), "id" = c("A", "A", "B", "B"), "number" = c(1, 3, 2, 5))
df
write.csv(df, "df.csv", row.names = F)
if (interactive()) {
ui <- fluidPage(
fileInput("file", "Upload Your File:"),
uiOutput("daterange"),
plotOutput("plot")
)
server <- function(input, output, session) {
df <- reactive({
req(input$file)
inFile <- input$file
read.csv(inFile$datapath, stringsAsFactors = F)
})
output$daterange <- renderUI({
dateRangeInput("daterange", "Select the date range:",
start = as.Date(min(df()$date), format = "%m/%d/%Y"),
end = as.Date(max(df()$date), format = "%m/%d/%Y"),
min = as.Date(min(df()$date), format = "%m/%d/%Y"),
max = as.Date(max(df()$date), format = "%m/%d/%Y")
)
})
output$plot <- renderPlot({
dfplot <- subset(df(), date >= input$daterange[1] & date <= input$daterange[2])
g <- ggplot(df(), aes(id, number)) +
geom_boxplot() +
theme_classic()
print(g)
})
}
shinyApp(ui=ui, server = server)
}
Well, it doesn't work for me, but I actually figured out a way by removing format = %m/%d/%Y i.e.
dates <- as.Date(df()$date)
dateRangeInput("daterange", "Select the date range:",
start = min(dates), end = max(dates),
min = min(dates), max = max(dates)
)
However, if I change for example a date from 1/2/2020 to 1/3/2020 and save the csv file, now the date range and plots don't show up again. This is making me really confusing. So, this shiny app only works with the data frame that was made within R, not the csv files that was made outside of R.
how are you reading the csv back in? unless you are using something sophisticated like the readr package, an apparent date field will probably be read in as a character string.
in the above I show that the base months function (to tell you the longform word of the month of the date) fails when passing a raw string , but succeeds when a date conversion has happened ( lubridate makes date conversion easy).
I am assuming you are editing the csv in excel. Could you try opening the csv file with notepad (or a text editor)? Save the changes and try re-running.
Not sure about why you are facing this issue, but csv does behave weird sometimes when opening with excel.