![](/img/trans.png)
[英]Shiny modules: how to access selected_rows with DT::datatables?
[英]How do I retrieve DataTables rows information with Shiny and DT?
我正在使用Shiny和DT包來顯示來自MySQL數據庫的過濾表。
簡而言之,我從用戶那里獲得輸入值,創建一個SQL查詢,捕獲輸出並將其顯示為DataTable。 可以使用DataTable列過濾器進一步過濾輸出,並且用戶應該能夠下載過濾后的數據集。
根據DT docs , input$table_rows_all
應該包含所顯示表的行索引。 但是,當我按下下載按鈕時,我得到的文件只有列名而沒有數據。
library(shiny)
library(DT)
library(RMySQL)
con <- dbConnect(MySQL(), user="myuser", host="myhost", dbname="mydb")
shinyServer(function(input, output) {
sqlOutput <- reactive({
sqlInput <- paste0("select * from mydb.mytable",
" where value < ", input$value,
";")
dbGetQuery(con, sqlInput)
})
output$table <- DT::renderDataTable(sqlOutput(), server=TRUE, rownames=FALSE, filter="top", options=list(pageLength=10))
output$download <- downloadHandler("filtered.data.txt", content = function(file) {
rows <- input$table_rows_all
write.table(sqlOutput()[rows, ], file, sep="\t", quote=FALSE, col.names=TRUE, row.names=FALSE)
})
})
在上面的代碼中,我將DBI::dbQuery()
的輸出保存到反應函數sqlOutput()
以便隨后將其傳遞給DT::renderDataTable()
和DT::renderDataTable()
shiny::downloadHandler()
。
我究竟做錯了什么? 我不確定,但是由於某種原因, input$table_rows_all
返回空向量。
非常感謝任何幫助,謝謝!
您的示例並非真正可復制,但是如果您只想能夠使用DT
從Shiny下載結果表,我可以看一下DT擴展 。 在那里,您可以看到可以使用tableTools
來選擇下載,而不是使用手動downloadHandler
。
這是演示功能的可復制示例:
注意 -您將需要在瀏覽器中安裝www
目錄和flash
。
library(shiny)
library(DT)
data(iris)
runApp(list(
ui = fluidPage(
sidebarLayout(
sidebarPanel("DT Download Example"),
mainPanel(
DT::dataTableOutput("mytable")
)
)
),
server = function(input, output) {
output$mytable <- DT::renderDataTable({
iris
},
extensions = 'TableTools',
rownames=FALSE,
filter="top",
options=list(dom = 'T<"clear">lfrtip',
tableTools = list(
sSwfPath = copySWF('www'),
aButtons = list('copy', 'print',
list(
sExtends = 'collection',
sButtonText = 'Save',
aButtons = c('csv','xls')
)
)
)
)
)
}))
這是代碼中相關部分的未經測試的版本:
output$table <- DT::renderDataTable({
sqlOutput()
}, server=TRUE,
extensions = 'TableTools',
rownames=FALSE,
filter="top",
options=list(pageLength=10,
dom = 'T<"clear">lfrtip',
tableTools = list(
sSwfPath = copySWF('www'),
aButtons = list('copy', 'print',
list(
sExtends = 'collection',
sButtonText = 'Save',
aButtons = c('csv','xls'))))))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.