Error in Selecting Variable from the Datatable

Hello Everbody,
I am working with the R Shiny currently and having a problem with selecting the variables from the Data. I have followed the suggestion from How to select variables using data table to create an input widget based on the uploaded data by using renderUI. But the problem is when i try to upload data with different columns/variable, an error appears:

Warning: Error in : Can't subset columns that don't exist.
x The columns SNo, VNo, dWeight_V2_V1, dWeight_V3_V1, dBodyFat_V2_V1, etc. don't exist.

this is how the code and the app looks like:

server <- function(input, output,session) {
  set.seed(122)
  
  # *** Read in data matrix ***
  df <- reactive({
    req(input$file1)
    # Avoid error message while file is not uploaded yet
    if (is.null(input$file1))  {return(NULL)}
    data<-read.csv(input$file1$datapath, header=input$header, sep=input$sep)
    return(data)
  })
  
###############################################################################################################################################################  
  
  # Dynamically generate UI input when data is uploaded ----
  
  output$checkbox <- renderUI({
    checkboxGroupInput(inputId = "select_var", 
                       label = "Select variables", 
                       choices = names(df()),
                       selected = names(df()))
  })

# Columns to print ----
  df_sel <- reactive({
    req(input$select_var)
    df_sel <- df() %>% select(input$select_var)
  })

 #Output for the Data Table
  output$contents <- DT::renderDataTable({
    datatable(df_sel(), options = list(pageLength = 12,
      initComplete = JS(
        "function(settings, json) {",
        "$(this.api().table().header()).css({'background-color': '#000', 'color': '#fff'});",
        "}")
    )) %>% formatRound(input$DecimalVariable, input$NumberDecimal)
  })

for the first datatable, it works very well and as long as i upload another data with the same variables/columns, it works fine.

But when I change the upload data file with different variable/columns, the app doesn't work anymore and comes the error as I said (above):

I guess it happens because the new variable or the new column can not replace the columns from the previous data. I am quite new with R Shiny and I hope someone can help me with this one. Thanks a lot!

try something like this

df_sel <- reactive({
  req(input$select_var)
  req(df())
  if(input$select_var %in% names(df()))
    df_sel <- df() %>% select(input$select_var)
  else 
    df_sel <- NULL # or df() or whatever...
  
  return(df_sel)
})

Hello Nirgrahamuk! Thank you very much! That works awesome!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.