我想对使用美元格式化的DataTable列进行排序(因此是一个字符)。我使用scales::dollar()
进行格式化。这会将字段转换为导致排序问题的字符(例如,"$8" > "$10"
)。
如何将字段排序为数字?或者,我可以将字段保留为数字,只打印美元格式吗?
app.R (需要Shiny 0.10.2)
server <- function(input, output) {
output$foo_table <- renderDataTable({
x <- seq(8000, 12000, by = 1000)
x <- scales::dollar(x)
d <- data.frame(x, stringsAsFactors = FALSE)
d
})
}
ui <- shinyUI(fluidPage(
mainPanel(dataTableOutput("foo_table"))
)
)
shinyApp(ui = ui, server = server)
答案 0 :(得分:3)
有点晚了,但DT Package现在有格式化函数,包括formatCurrency:
# format the columns A and C as currency, and D as percentages
datatable(m) %>% formatCurrency(c('A', 'C')) %>% formatPercentage('D', 2)
从“功能”页面:
在幕后,这些格式化函数只是rowCallback选项的包装器,用于生成适当的JavaScript代码。 类似地,有一个formatDate()函数可用于格式化日期/时间列。它有一个方法参数,它从可能的转换方法列表中获取值:toDateString,toISOString,toLocaleDateString,toLocaleString,toLocaleTimeString,toString,toTimeString,toUTCString。
答案 1 :(得分:1)
gtools包中的mixedsort和mixedorder函数可以做到这一点:
x <- seq(8000, 12000, by = 1000)
x <- scales::dollar(x)
d <- data.frame(x)
mixedsort(d$x) # not much of a test but also give same results with mixedsort(rev(d$x))
[1] $8,000 $9,000 $10,000 $11,000 $12,000
Levels: $10,000 $11,000 $12,000 $8,000 $9,000
请注意,您的data.frame调用已创建因子。你可能不希望这样,如果不是,应该包括stringsAsFactors = FALSE。我在帮助页面中没有看到任何关于逗号的提及,因此您可能希望在gsub("[,]", "", d$x)
之前应用mixedsort
。
答案 2 :(得分:1)
从DataTables 1.10开始,您应该可以使用货币http://datatables.net/reference/option/columns.type进行排序。在选项中,为列索引零提供type = 'num-fmt'
就足够了。这与`选项中的columnDefs = list(list(targets = c(0), type = "num-fmt"))
相对应。
以下应该有效但不适合我:
library(shiny)
server <- function(input, output) {
output$foo_table <- renderDataTable({
x <- seq(8000, 12000, by = 1000)
x <- scales::dollar(x)
d <- data.frame(x)
d
}
, options = list(
columnDefs = list(list(targets = c(0), type = "num-fmt"))
)
)
}
ui <- shinyUI(fluidPage(
mainPanel(dataTableOutput("foo_table"))
)
)
shinyApp(ui = ui, server = server)
也许@yihui可以解决这个问题。