Search code examples
rshinydatatabledtr-colnames

Why are my column names not changing when I set the colnames in DT datable and giving me an error that ' names in the 'escape' argument not found'?


I want to change how my column names are displayed in my R Shiny App's datable, but I do not want to change how R responds to them under the hood. When I try using datatable's colnames argument, I get the following error:

Warning: Error in convertIdx: Some column names in the 'escape' argument not found in data

Which, technically, makes sense because I am changing the column names, but I thought that this was just an aesthetic change (and that's what I want).

Here's a simple app that reproduces the error:

library(shiny)
library(dplyr)
library(DT)
ui <- fluidRow(
    column(12,
           
           DT::dataTableOutput("table")

        
    )
)

server <- function(input, output) {
    
    raw_data <- reactive({tibble(start_date = c("2020-01-01", "2020-01-09", "2020-01-30"),
                       choice = c("A", "B", "C"))
    }) #Note: I'm aware this doesn't need to be reactive here, but in my actual data, the underlying data are reactive, so I want to mirror my real world scenario here.
    
    output$table <- DT::renderDataTable({
        datatable(raw_data(),
                  colnames = c("start_date" = "Date to Start", "choice" = "Letter Options"))
    })
    

    
}

shinyApp(ui = ui, server = server)

Solution

  • The order in columns need to be opposite, it is newname = oldname.

    library(shiny)
    library(dplyr)
    library(DT)
    
    ui <- fluidRow(
      column(12,
             DT::dataTableOutput("table")
      )
    )
    
    server <- function(input, output) {
      
      raw_data <- reactive({tibble(start_date = c("2020-01-01", "2020-01-09", "2020-01-30"),
                                   choice = c("A", "B", "C"))
      }) 
      
      output$table <- DT::renderDataTable({
        datatable(raw_data(),
                  colnames = c("Date to Start" = "start_date", "Letter Options" = "choice"))
      })
    }
    
    shinyApp(ui = ui, server = server)