Ordering factors in data table using DT package

♀尐吖头ヾ 提交于 2019-12-22 10:37:40

问题


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))))


来源:https://stackoverflow.com/questions/35657271/ordering-factors-in-data-table-using-dt-package

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!