为存储为字符串的数字自定义排序 R 数据表列
Custom sorting of R datatable column for numbers stored as strings
我有一个闪亮的仪表板,我在其中使用 DataTable 包(代码严格遵循 Shiny documentation 中的方法)来构建我的 tables。
一切正常,但出于美观原因,我想用逗号分隔符显示数字,因此 1000000
呈现为 1,000,000
.
到目前为止,我的方法只是重新格式化数字列,例如:
table$col <- formatC(table$col, format="d", big.mark=',')
这工作正常,但是当我想使用标准函数对网页中的 table 进行排序时,我得到了按字典顺序排序的结果,因为数字现在被编码为字符串。
是否可以修改 table 排序函数,或者以某种方式对数字进行编码,使它们使用逗号分隔符呈现,但对于这些本质上是数字的列,排序将按预期进行?
如果有用,可以将其复制到 server.R 文件中:
table <- morley
table$Speed <- formatC(table$Speed, format="d", big.mark=',')
output$table <- DT::renderDataTable(
DT::datatable(table)
)
第 4.5 节 - 此 DT 文档的行呈现有您的答案:
https://rstudio.github.io/DT/options.html
当我需要通过 DT (DataTable) 包格式化数值时,我使用 formatCurrency
并确保用空字符串指定 currency
参数。从那里,可以使用 digits
和 mark
.
等参数调整输出
下面是这个函数的一个例子:
library(dplyr)
data = data.frame(
value1 = runif(10) * 10000,
value2 = runif(10) * 100000,
stringsAsFactors = F
)
DT::datatable(data) %>%
DT::formatCurrency(columns = "value1", currency = "", mark = ",") %>%
DT::formatCurrency(columns = "value2", currency = "", mark = " ", digits = 0)
输出为here
我有一个闪亮的仪表板,我在其中使用 DataTable 包(代码严格遵循 Shiny documentation 中的方法)来构建我的 tables。
一切正常,但出于美观原因,我想用逗号分隔符显示数字,因此 1000000
呈现为 1,000,000
.
到目前为止,我的方法只是重新格式化数字列,例如:
table$col <- formatC(table$col, format="d", big.mark=',')
这工作正常,但是当我想使用标准函数对网页中的 table 进行排序时,我得到了按字典顺序排序的结果,因为数字现在被编码为字符串。
是否可以修改 table 排序函数,或者以某种方式对数字进行编码,使它们使用逗号分隔符呈现,但对于这些本质上是数字的列,排序将按预期进行?
如果有用,可以将其复制到 server.R 文件中:
table <- morley
table$Speed <- formatC(table$Speed, format="d", big.mark=',')
output$table <- DT::renderDataTable(
DT::datatable(table)
)
第 4.5 节 - 此 DT 文档的行呈现有您的答案: https://rstudio.github.io/DT/options.html
当我需要通过 DT (DataTable) 包格式化数值时,我使用 formatCurrency
并确保用空字符串指定 currency
参数。从那里,可以使用 digits
和 mark
.
下面是这个函数的一个例子:
library(dplyr)
data = data.frame(
value1 = runif(10) * 10000,
value2 = runif(10) * 100000,
stringsAsFactors = F
)
DT::datatable(data) %>%
DT::formatCurrency(columns = "value1", currency = "", mark = ",") %>%
DT::formatCurrency(columns = "value2", currency = "", mark = " ", digits = 0)
输出为here