Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove end users ability to sort upon a column

Tags:

r

dt

I have a large datatables object and I want to limit the sortability of certain columns. I think I have to use the options argument, but my knowledge of JavaScript is not at the point where I know how to integrate it with arguments of a function.

I have the following code as an example:

library(DT)

# Create Columns and dataframe
letters <- c("a", "b", "c", "d")
numbers <- c(1, 2, 3, 4)
words <- c("the", "quick", "brown", "fox")
df <- data.frame(letters, numbers, words, stringsAsFactors = FALSE)

# Create Data Table
htmlDf <- datatable(df, rownames = FALSE)

I also have the following code snippet that I have tried to massage into the options argument. The small code chunk came from https://datatables.net/reference/option/columns.orderable.

    $('#example').dataTable( {
      "columns": [
        {null,
         "orderable": false },
         null,
                ]
    } );

For the purpose of this question, suppose I wish to remove the ability to sort on the "numbers" column.

Thanks!

Note: this is not for a Shiny App.

like image 783
gvan Avatar asked Oct 26 '25 06:10

gvan


1 Answers

The site for the R package DT provides some great tutorials on how to convert the javascript options from datatables into R syntax.

Essentially what you do is pass nested, named lists which mirror the structure of the JavaScript code into the options argument for the datatable function. So in your case, you'd want to do this:

htmlDf <- datatable(df,
                    rownames = FALSE,
                    options = list(
                        columnDefs = list(
                            list(orderable = F,
                                 targets = c(1))
                            )
                        )
                    )

Which nicely applies the orderable = FALSE condition to column 1. Note that you have to use JavaScript style 0-indexing rather than R style 1-indexing:

enter image description here

like image 144
divibisan Avatar answered Oct 28 '25 19:10

divibisan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!