-->

Ordering factors in data table using DT package

2019-07-17 16:11发布

问题:

I have data that I want to display in 5% increments, such as 5-10%, 10-15%, etc. To do this, I have a data frame that stores them as a factor, with the levels being the midpoint of the range, and the label being the range to display. For example, the level 12.5 would be labeled 10-15%.

However, I'm having trouble sorting this correctly using a datatable.

library('DT')
example <- data.frame(name = c('A', 'B', 'C', 'D'),
                  value = factor(c(7.5, 12.5, 7.5, 17.5),
                                  levels = c(7.5, 12.5, 17.5),
                                  labels = c('5-10%', '10-15%', '15-20%')))

datatable(example,
      rownames = FALSE,
      options = list(order = list(1, 'asc')))


As you can see, it appears to be sorting off of the first number of the character string, rather than sorting by the level of the factor.

Any ideas on how I can get the data table to sort off of the factor levels, rather than the character string? (Other than ordering the data frame before passing it into the data table - I would like this to be correctly sortable in either direction by clicking the sort arrow)

回答1:

You could use a hidden column with the numeric value of the factor and sort the factors according to that hidden column:

library('DT')
value <- factor(c(7.5, 12.5, 7.5, 17.5),
                levels = c(7.5, 12.5, 17.5),
                labels = c('5-10%', '10-15%', '15-20%'))

example <- data.frame(name = c('A', 'B', 'C', 'D'),
                      value = value,
                      levels=as.numeric(value))

datatable(example,
          rownames = FALSE,
          options = list(columnDefs=list(list(orderData=2,targets=1),
                                         list(visible=FALSE,targets=2))))


标签: r sorting shiny dt