1

Below, I have some basic code for a shiny app I'm creating. I want to take the user uploaded file, split the dataset into two sections - one based for the first inputted date range and one for the second. Then, compute sums for a different column in the dataset based on those time periods. I can get all of this to work, but my question is if I can somehow use the input$daterange1 and input$daterange2 to title the columns of the datatable, so the user know which sums are associated with which time periods. So below, can I somehow change "Sum 1" and "Sum 2" to the user inputted date ranges?

ui <- fluidPage(
sidebarLayout(
 sidebarPanel(
  fileInput("file1", "Choose CSV File",
            accept=".csv"),
  dateRangeInput("daterange1", "Specify First Date Range", start="2016-12-06", end=Sys.Date()),
  dateRangeInput("daterange2", "Specify Second Date Range", start=(Sys.Date()-30), end=Sys.Date(),
                 min="2016-12-06", max=Sys.Date()),
  actionButton("submit", "Submit"),
  width=3
),

mainPanel(
  tabsetPanel(
    tabPanel("Sum", DT::dataTableOutput("tab"), downloadButton("dltab", "Download"))
 )
)

Server

server <- function(input, output, session) {
   observeEvent(input$submit,{
   file1=input$file1
   if (is.null(file1)){
      return(NULL)
  }
  df<-read.csv(file1$datapath, fileEncoding = "UTF-8-BOM")
  df$FAIL<-ifelse(df$OPERATION_STATUS %in% "FAIL",1,0)
df$CATEGORY<-sub("\\s+\\d+", "", df$CRIT_CODE)
df$DATE<-as.Date(df$DATE)

audit<-df
setDT(audit)
audit[,group_o := DATE >= as.Date(input$daterange1[1]) & DATE <= as.Date(input$daterange1[2])]
audit[,group_i := DATE >= as.Date(input$daterange2[1]) & DATE <= as.Date(input$daterange2[2])]
dt<-(audit[, .(
  "Sum 1" = sum(OPERATION_STATUS[group_o]),
  "Sum 2" = sum(OPERATION_STATUS[group_i]),
  "Difference of Sums" = (sum(OPERATION_STATUS[group_o]) - sum(OPERATION_STATUS[group_i])),
  keyby = .("Area" = CRIT_CODE)])
output$tab<-DT::renderDataTable({
  datatable(dt)
})
Lost
  • 331
  • 1
  • 12

1 Answers1

1

We need to create reactive variables as shown below, then once the file has been loaded in use these variables as the names of the columns.

 server<-function(input,output,session){

  colA <- NULL
  colB <- NULL

 makeReactiveBinding("colA")
 makeReactiveBinding("colB")

  observeEvent(input$daterange1, { 
    colA<<-input$daterange1
    colA<<-paste(colA[1],"-",colA[2])
    colA<<-as.character(colA)
    print(colA)
    })

  observeEvent(input$daterange2, { 
    colB<<-input$daterange2
    colB<<-paste(colB[1],"-",colB[2])
    colB<<-as.character(colB)
    print(colB)
  })


observeEvent(input$submit, { .......
  names(dt)<-c(colA,colB)

})

}

Note that input$daterange1/2 will give us two variables, because it is a range. Therefore, we paste together the first and second element of colA/B to get a daterange in one character string.

Chabo
  • 2,842
  • 3
  • 17
  • 32