使用DT软件包的数据表中的订购因子 [英] Ordering factors in data table using DT package
问题描述
我有一些数据想要以5%的增量显示,例如5-10%,10-15%等.为此,我有一个数据框将其存储为一个因子,其级别为范围的中点,标签是要显示的范围.例如,级别12.5将标记为10-15%.
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)
推荐答案
您可以使用带有因子数值的隐藏列,并根据该隐藏列对因子进行排序:
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))))
这篇关于使用DT软件包的数据表中的订购因子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!