2014-10-26 35 views
5

我想排序格式化爲美元(因此是一個字符)的DataTable列。我已經使用scales::dollar()進行格式化。這將字段轉換爲導致排序問題的字符(例如,"$8" > "$10")。打印就像一個字符,但像Shiny和DataTable中的數字排序

如何將字段排序爲數字?或者,我可以將字段保留爲數字,只需使用美元格式打印?

app.R(需要閃亮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) 

回答

1

有點晚,但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

在包gtools的mixedsort和mixedorder功能,可以這樣做:你data.frame調用創建

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 

公告因素。你可能不想要那個,如果不是,應該包含stringsAsFactors = FALSE。我在幫助頁面中看不到有關逗號的任何提及,因此您可能需要在mixedsort之前應用gsub("[,]", "", d$x)

+0

'gtools :: mixedsort()'看起來非常方便。但是這並不能解決讓Shiny中的dataTable正確排序的問題。 – davechilders 2014-10-27 02:04:38

+0

對不起。我不是一個足夠有經驗的Shiny用戶來解析這個聲明 – 2014-10-27 02:53:33

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可以擺脫對這個問題的一些情況。

+0

'renderDataTable'這個選項是我正在尋找的東西的類型。無法弄清楚爲什麼這不起作用。也許這可以通過文字JavaScript來完成? – davechilders 2014-10-27 13:16:30