【发布时间】:2016-02-14 03:41:04
【问题描述】:
我正在使用 DT 包中的 shiny 和 renderDataTable 函数在我的 web 应用程序中显示一个表。排序时,似乎将数字视为字符串,按第一个数字排序,然后按第二个数字排序,依此类推,即应该排序为 1、2、5、100、250 的内容将排序为 1、100、2、250、5
我尝试在读取 csv 时指定 colClasses,但似乎不起作用。
server.R 显示,我的 ui.R 只是一个 dataTableOutput
library(DT)
library(dplyr)
date <- format(Sys.Date() - 1, '%Y_%m_%d')
date2 <- format(Sys.Date() - 2, '%Y_%m_%d')
# Read data in
tab1 <- read.csv(paste0(date, '_tabs.csv'), stringsAsFactors = FALSE, colClasses = c('character', rep('integer', 9)))
tab1 <- na.omit(tab1)
tab2 <- read.csv(paste0(date2, '_tabs.csv'), stringsAsFactors = FALSE, colClasses = c('character', rep('numeric', 9)))
# Ensuring both tables have matching values for country
tab3 <- tab2[tab2$X %in% tab1$X, ]
missingr <- setdiff(tab1$X, tab3$X)
for (j in missingr) {
tab3 <- rbind(tab3, rep(0, length(tab1)))
tab3[nrow(tab3), 1] <- j
}
# Sorting by country and creating a new dataframe of differences
Country <- tab1$X
tab1 <- arrange(tab1, X)
tab3 <- arrange(tab3, X)
tab1 <- tab1[, !(names(tab1) %in% 'X')]
tab3 <- tab3[, !(names(tab3) %in% 'X')]
tab2 <- tab1 - tab3
# Adding total column and country column to dataframes
c1 <- c('Total', colSums(tab1))
c2 <- c('Total', colSums(tab2))
rownames(tab2) <- Country
tab2 <- data.frame(Country, tab2)
tab1 <- data.frame(Country, tab1)
tab1 <- tab1[tab1$total > 100, ]
tab2 <- tab2[tab2$Country %in% tab1$Country, ]
tab1 <- rbind(tab1, c1)
tab2 <- rbind(tab2, c2)
shinyServer(function(input, output) {
output$tab1 <- renderDataTable({tab1},
rownames = FALSE, options = list(lengthMenu = list(c(20, 10, -1), c('20', '10', 'All')),
initComplete = JS("function(settings, json) {","$(this.api().table().header()).css({'background-color': '#000', 'color': '#fff'});","}"),
autoWidth = TRUE,
columnDefs = list(list(width = '200px', targets = "_all"))
))
output$tab2 <- renderDataTable({tab2},
rownames = FALSE, options = list(lengthMenu = list(c(20, 10, -1), c('20', '10', 'All')),
initComplete = JS("function(settings, json) {","$(this.api().table().header()).css({'background-color': '#000', 'color': '#fff'});","}"),
autowidth = TRUE,
columnDefs = list(list(width = '200px', targets = "_all"))
))
}
)
【问题讨论】:
-
您在哪里订购桌子?
renderDataTable默认情况下不对表进行排序。 rstudio.github.io/DT/options.html 的第 4.1 节解释了order-option。 -
点击一列对其进行排序,就像在您刚刚链接的页面上一样,按最左边的列排序的默认选项是我最初想要的(按国家排序),然后用户可以单击一列对它们进行排序。
-
尝试在您创建的表上使用
str。它会告诉你你有什么样的数据并且将输出添加到你的问题中会很有帮助。 -
我没有足够的代表来发布图片,但这是链接,直到有人将其删除i.imgur.com/No7SiJT.png pic 显示了当您单击最左侧的数字列进行排序时会发生什么。读取 csv 文件时的 X 列是国家/地区代码,因此无论如何都需要是字符。其余列应为 nums/ints