I would like to add another condition in the code below. Notice that the daterange
is activated when the Excel
option is chosen and a file is loaded in fileInput
- this is working fine. However, I would also like to activate daterange
, after I get the connection to the database, that is, after I press the database
option. How do I adjust this in code?
library(shiny)
library(dplyr)
library(shinythemes)
ui <- fluidPage(
shiny::navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
br(),
tabPanel("PAGE1",
sidebarLayout(
sidebarPanel(
radioButtons("button",
label = h3("Data source"),
choices = list("Excel" = "Excel",
"Database" = "database"),
selected = "File"),
uiOutput('fileInput'),
conditionalPanel(
condition = "output.fileUploaded == true",
uiOutput("daterange"),
)),
mainPanel(
dataTableOutput('table')
)))))
server <- function(input, output) {
observe({
if(is.null(input$button)) {
}else if (input$button =="Excel"){
output$fileInput <- renderUI({
fileInput("file",h4("Import file"), multiple = T, accept = ".xlsx")
})
} else if(input$button=="database"){
con <- DBI::dbConnect(odbc::odbc(),
Driver = "[your driver's name]",
Server = "[your server's path]",
Database = "[your database's name]",
UID = rstudioapi::askForPassword("Database user"),
PWD = rstudioapi::askForPassword("Database password"),
Port = 1433)
data <-tbl(con, in_schema("dbo", "date1")) %>%
collect()
}
})
data <- reactive({
if (is.null(input$file)) {
return(NULL)
}
else {
df3 <- read_excel(input$file$datapath)
validate(need(all(c('date1', 'date2') %in% colnames(df3)), "Incorrect file"))
df4 <- df3 %>% mutate_if(~inherits(., what = "POSIXct"), as.Date)
return(df4)
}
})
output$fileUploaded <- reactive({
return(!is.null(data()))
})
outputOptions(output, 'fileUploaded', suspendWhenHidden=FALSE)
output$daterange <- renderUI({
req(data())
dateRangeInput("daterange1", "Period you want to see:",
start = min(data()$date2),
end = max(data()$date2))
})
data_subset <- reactive({
req(input$daterange1)
days <- seq(input$daterange1[1], input$daterange1[2], by = 'day')
subset(data(), date2 %in% days)
})
output$table <- renderDataTable({
data_subset()
})
}
shinyApp(ui = ui, server = server)