Upload data and code adaptation

Ottavia M. Epifania

People want to use the app for their own data – the code needs to be as fluid as possible and to allow the users to upload their data

fileInput("file", "Select a CSV file", accept = "csv")

To be flexible enough to allow for the customization of the settings based on the characteristics of the dataset

The UI and the server need to communicate differently

A flow in a flow

Step 0

Step 1

Step 2

Step 3

ui = fluidPage(
  sidebarLayout(
    sidebarPanel(
        fileInput("file", "", accept = c("csv")),
        radioButtons("sep",
                     "Choose column separator",
                     c(";" = ";", "," = ",")),
      actionButton("load", "Upload data"),
      uiOutput("x_ui"),
      uiOutput("y_ui"),
 actionButton("analyze", "Analyze data")
    ),
    
    mainPanel(
      plotOutput("graph"),
      verbatimTextOutput("summary")
    )
  )
)
1
File input
2
Specify the separator to be used in the read.csv function
3
First action button to upload the dataset
4
Define the UI container for the names of the dataset variables, taken from the dataset itself
5
Second button that actually activates the selection of the selected columns and starts the analysis
server <- function(input, output, session){
  dataInput <- eventReactive(input$load, {
      read.csv(input$file$datapath, sep = input$sep)
  })
  vars <- reactive({
    names(dataInput())
  })
  output$x_ui <- renderUI({
    selectInput(
      "x",
      "X variable:",
      choices = vars(),
      selected = vars()[1]
    )
  })
  output$y_ui <- renderUI({
    selectInput(
      "y",
      "Y variable:",
      choices = vars(),
      selected = vars()[min(2, length(vars()))]
    )
  })
  
  newdata <- eventReactive(input$analyze, {
    df <- dataInput()
    df[, c(input$x, input$y), drop = FALSE]
  })

  output$graph <- renderPlot({
    df <- newdata()   
    x <- df[[1]]
    y <- df[[2]]
    if (is.factor(x) || is.character(x)) {
      boxplot(y ~ x,
              xlab = "Group",
              ylab = "Value")
    } else {
      plot(x, y)
    }
  })
  output$summary <- renderPrint({
    df <- newdata()
    summary(df)
  })
}
1
Define the reactive environment and import the correct dataset with the dedicated function
2
Extract the column names to populate the ui setting configuration
3
Use the renderUI to actually populate the response options of the x variable
4
Use the renderUI to actually populate the response options of the y variable
5
Select the columns of the dataframe that are actually used for the analysis
shinyApp(ui, server)