'Plot by the uploaded file in R shiny

I was making a tool to draw a plot by the user uploaded file. But when I tested it, I found a problem that sometimes when inputting file, R will substitute the space and special characters to be a dot (.), but sometimes substitute to the bottom line(_). Hence when I want to control the x-axis and y-axis, sometimes it couldn't work, for example, I use the Co2_emission data, the special characters, and the space of heading becomes a dot, even though I turn the colnames to be the same as it, it still couldn't work. But when I used another data that has no special character but only space, and I change the space of colnames inside the shiny-server to a bottom line, it could work(could draw a plot). I wonder why this would happen. My English isn't good, so if something isn't expressed enough, I will try to answer you right away.

Here is my testing files.

https://www.kaggle.com/debajyotipodder/co2-emission-by-vehicles (can't work)

https://www.kaggle.com/kkhandekar/global-sea-level-1993-2021 (work)

Here is my code.

library(shiny)
library(stringr)
library(echarts4r)
library(thematic)
library(bs4Dash)
library(DT)
library(ggplot2)
library(plotly)
library(shinyWidgets)

server <- function(input, output) {
  set.seed(122)
  histdata <- rnorm(500)
  # 上傳資料 1
  data1 <- reactive({
    shiny::req(input$file1)
    ext <- tools::file_ext(input$file1$name)
    switch(
      ext,
      csv = vroom::vroom(input$file1$datapath, delim = ","),
      tsv = vroom::vroom(input$file1$datapath, delim = "\t"),
      validate("Invaliod file")
    )
  })
  # 上傳資料 2
  data2 <- reactive({
    shiny::req(input$file2)
    ext <- tools::file_ext(input$file2$name)
    switch(
      ext,
      csv = vroom::vroom(input$file2$datapath, delim = ","),
      tsv = vroom::vroom(input$file2$datapath, delim = "\t"),
      validate("Invaliod file")
    )
  })
  # 上傳資料 3
  data3 <- reactive({
    shiny::req(input$file3)
    ext <- tools::file_ext(input$file3$name)
    switch(
      ext,
      csv = vroom::vroom(input$file3$datapath, delim = ","),
      tsv = vroom::vroom(input$file3$datapath, delim = "\t"),
      validate("Invaliod file")
    )
  })
  # 輸出資料1標題
  output$data1_title <- renderText({
    str_sub(as.character(input$file1$name),
            start = 1,
            end = 8)
  })
  # 輸出資料2標題
  output$data2_title <- renderText({
    str_sub(as.character(input$file2$name),
            start = 1,
            end = 8)
  })
  # 輸出資料2標題
  output$data3_title <- renderText({
    str_sub(as.character(input$file3$name),
            start = 1,
            end = 8)
  })
  # 輸出資料 1
  output$data1_table <- renderDT({
    data1()
  })
  # 輸出資料 2
  output$data2_table <- renderDT({
    data2()
  })
  # 輸出資料 3
  output$data3_table <- renderDT({
    data3()
  })
  # 變數 Y
  output$select_x <- renderUI({
    if (input$data_choose == "Data1") {
      List_x = gsub("[[:punct:][:blank:]]", "_", colnames(data1()))
    } else if (input$data_choose == "Data2") {
      List_x = gsub("[[:punct:][:blank:]]", "_", colnames(data2()))
    } else if (input$data_choose == "Data3") {
      List_x = gsub("[[:punct:][:blank:]]", "_", colnames(data3()))
    }
    pickerInput(
      "select_x_axis",
      "X-axis",
      choices = List_x,
      options = list(title = "Choose X axis")
    )
  })
  # 變數 Y
  output$select_y <- renderUI({
    if (input$type == "Scatter Plot") {
      if (input$data_choose == "Data1") {
        List_y = gsub("[[:punct:][:blank:]]", "_", colnames(data1()))
      } else if (input$data_choose == "Data2") {
        List_y = gsub("[[:punct:][:blank:]]", "_", colnames(data2()))
      } else if (input$data_choose == "Data3") {
        List_y = gsub("[[:punct:][:blank:]]", "_", colnames(data3()))
      }
      List_Wo_x =  List_y[List_y != input$select_x_axis]
      pickerInput(
        "select_y_axis",
        "Y-axis",
        choices =  List_Wo_x,
        options = list(title = "Choose Y axis")
      )
    }
  })
  # 是否要額外變數
  output$others_variable_switch <- renderUI({
    if (is.null(input$type)){
      ""
    } else if (!is.null(input$type)) {
      materialSwitch(inputId = "more_variable",
                     label = "More variable",
                     value = F)
    }
  })
  # 額外變數選擇
  output$others_variable_choices <- renderUI({
    if (input$more_variable == FALSE){
      ""
    } else if (input$more_variable == TRUE) {
      checkboxGroupButtons(
        inputId = "OthersVariable",
        label = "More Variable :",
        choices = c(
          `<i class='fa fa-palette'></i>` = "color",
          `<i class='fa fa-shapes'></i>` = "shape",
          `<i class='fa fa-expand-arrows-alt'></i>` = "size"
        ),
        selected = "color",
        justified = TRUE,
        checkIcon = list(yes = icon("ok",
                                    lib = "glyphicon"))
      )
    }
  })
  # 變數 color
  output$others_variable_color <- renderUI({
    if (is.null(input$OthersVariable)) {
      ""
    } else if (input$OthersVariable == "color") {
      if (input$data_choose == "Data1") {
        List_color = colnames(data1())
      } else if (input$data_choose == "Data2") {
        List_color = colnames(data2())
      } else if (input$data_choose == "Data3") {
        List_color = colnames(data3())
      }
      choice_color = List_color[List_color != input$select_x_axis &
                                   List_color != input$select_y_axis]
      pickerInput(
        "select_color",
        "Color Variable",
        choices = choice_color,
        options = list(title = "Choose color variable")
      )
    } else {
      ""
    }
  })
  # 變數 shape
  output$others_variable_shape <- renderUI({
    if (is.null(input$OthersVariable)) {
    ""
  } else if (input$OthersVariable == "shape") {
      if (input$data_choose == "Data1") {
        List_shape = colnames(data1())
      } else if (input$data_choose == "Data2") {
        List_shape = colnames(data2())
      } else if (input$data_choose == "Data3") {
        List_shape = colnames(data3())
      }
      choice_shape =  List_shape[List_shape != input$select_x_axis &
                                   List_shape != input$select_y_axis]
      pickerInput(
        "select_shape",
        "Shape Variable",
        choices = choice_shape,
        options = list(title = "Choose shape variable") 
      )
    } else if (is.null(input$OthersVariable)) {
      ""
    }
  })
  # 變數 size
  output$others_variable_size <- renderUI({
    if (is.null(input$OthersVariable)) {
      ""
    } else if (input$OthersVariable == "size") {
      if (input$data_choose == "Data1") {
        List_size = colnames(data1())
      } else if (input$data_choose == "Data2") {
        List_size = colnames(data2())
      } else if (input$data_choose == "Data3") {
        List_size = colnames(data3())
      }
      choice_size =  List_size[List_size != input$select_x_axis &
                                 List_size != input$select_y_axis]
      pickerInput(
        "select_size",
        "Size Variable",
        choices = choice_size,
        options = list(title = "Choose size variable")
      )
    } else {
      ""
    }
  })
  # 作圖
   p <- eventReactive(input$DrawButton, {
    if (input$data_choose == "Data1") {
      ggplot(data1(), aes_string(input$select_x_axis, input$select_y_axis)) +
        geom_point() +
        geom_smooth()
    } else if (input$data_choose == "Data2") {
      ggplot(data2(), aes_string(input$select_x_axis, input$select_y_axis)) +
        geom_point() +
        geom_smooth()
    } else if (input$data_choose == "Data3") {
      ggplot(data3(), aes_string(input$select_x_axis, input$select_y_axis)) +
        geom_point() +
        geom_smooth()
    }
   })
   output$plot <- renderPlot({
     p()
   })
}
ui <- dashboardPage(
  # 標題
  dashboardHeader(
    title = span("Data Visualization",
    style = "font-weight: bold; font-size: 31px")
  ),
  # 選單
  dashboardSidebar(sidebarMenu(
    menuItem(
      "Data",
      tabName = "data_upload",
      icon = icon(name = "database", lib = "font-awesome")
    ),
    menuItem(
      "Graph",
      tabName = "graph",
      icon = icon(name = "stats", lib = "glyphicon")
    )
  )),
  # 主要頁面
  dashboardBody(# 資料上傳以及資料處理區
    tabItems(
      tabItem(tabName = "data_upload",
              fluidRow(
                # 資料上傳
                box(
                  title = span("Upload File",
                  style = "font-weight: bold; font-size: 25px"),
                  # 上傳資料 1
                  fileInput("file1", "Data 1", accept = c(".csv", ".tsv")),
                  # 上傳資料 2
                  fileInput("file2", "Data 2", accept = c(".csv", ".tsv")),
                  fileInput("file3", "Data 3", accept = c(".csv", ".tsv")),
                  width = 4
                ),
                # 檢視資料
                box(
                  title = span("Data Table",
                  style = "font-weight: bold; font-size: 25px"),
                  tabsetPanel(
                    # 資料 1
                    tabPanel(textOutput("data1_title"),
                    DTOutput("data1_table")),
                    # 資料 2
                    tabPanel(textOutput("data2_title"),
                    DTOutput("data2_table")),
                    tabPanel(textOutput("data3_title"),
                    DTOutput("data3_table"))
                  ),
                  width = 8
                )
              )),
      # 視覺化區
      tabItem(tabName = "graph",
              fluidRow(
                # 控制面板
                box(
                  title = span("Control Panel",
                  style = "font-weight: bold; font-size: 25px"),
                  radioGroupButtons(
                    "graph_choose",
                    label = "Choose graph",
                    choices = c("Graph1", "Graph2", "Graph3"),
                    justified = TRUE,
                    checkIcon = list(yes = icon("ok",
                                                lib = "glyphicon"))
                  ),
                  # 選擇資料
                  radioGroupButtons(
                    "data_choose",
                    label = "Choose data",
                    choices = c("Data1", "Data2", "Data3"),
                    justified =  TRUE,
                    checkIcon = list(yes = icon("ok",
                                                lib = "glyphicon"))
                  ),
                  pickerInput(
                    inputId = "type",
                    label = "Type",
                    choices = c("Scatter Plot", "Histogram", "Pie Chart")
                  ),
                  uiOutput("select_x"),
                  uiOutput("select_y"),
                  uiOutput("others_variable_switch"),
                  uiOutput("others_variable_choices"),
                  uiOutput("others_variable_color"),
                  uiOutput("others_variable_shape"),
                  uiOutput("others_variable_size"),
                  # 作圖按鈕
                  actionButton(
                    "ResetButton",
                    "Reset",
                    icon = icon("eraser", lib = "font-awesome")),
                  actionButton(
                    "DrawButton",
                    "Draw",
                    icon = icon("drafting-compass", lib = "font-awesome")
                  ),
                  width = 5
                ),
                # 圖
                box(
                  title = span("Graph",
                  style = "font-weight: bold; font-size: 25px"),
                  plotOutput("plot"),
                  width = 7
                )
              ))
    ))
)



shinyApp(ui, server)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source