17

I would like to change the column names of a datable at the very last step before I output it in a Shiny app. The display names are quite long, and I do not want to change them while I'm manipulating the datatable. There are a lot more formatting changes to the datatable than below in my actual dataset.

Here is a dummy dataset:

library(DT)
test.df <- data.frame(a = runif(10), b = 21:20, c = 31:30, d = 31:40)
test.dt <- datatable(test.df) %>% formatPercentage('a', 0) %>% formatCurrency('c', '$')

Now, how would I change the column names to c('Col1', 'Col2', 'Col3', 'Col4')? Again, I would like this to be the last step before I output the datatable with a renderDataTable function.

If there's a way to create column aliases as opposed to changing the actual column names, that would work as well.

matsuo_basho
  • 2,833
  • 8
  • 26
  • 47
  • 1
    Just use the `colnames` argument of `datatable`, which will create a display name like you wanted. Please refer to the documentation. – Xiongbing Jin May 12 '16 at 20:34
  • But test.df is already a datatable. The documentation has colnames as an argument in the datatables function. (https://rstudio.github.io/DT/) I don't see how to include the column names at the very end, after I've already converted the df into a datatable. – matsuo_basho May 12 '16 at 20:58

1 Answers1

19

Just use the colnames argument of datatable. This only changes the display name, so you can still use the original column names in your formatting code.

test.dt <- datatable(test.df, colnames=c("aa", "cc")) %>% formatPercentage('a', 0) %>% formatCurrency('c', '$')
Xiongbing Jin
  • 11,779
  • 3
  • 47
  • 41
  • Works beautifully, didn't realize colnames only changes the display of the columns, not the underlying names. – matsuo_basho May 13 '16 at 13:22
  • 3
    It seems the behaviors of format* function has been changed as of DT version 0.2 released on Aug 8, 2016. The provided example no longer works with v0.2. Now the format* functions expect the new names of the renamed columns. In other words, display names must be used to select columns in the format* functions. – ruiyiz May 17 '17 at 15:40