I am creating a Shiny app that displays data.frame information at the top of the screen and specific variable stats at the bottom. The user can navigate the data.frame columns by interacting with a DT::datatable
object.
When a user clicks on a variable, detailed information is presented that can be edited. I would like this information to be updated and reflected in the datatable. My problem is that when I update the table, it is rendered and shown starting at the very beginning. How can I preserve the page and row selection of the datatable after making edits?
Here is a minimal working example that shows the mtcars dataset in a DT::datatable
. I have some controls that update fields. Notice that datatable is re-rendered back to the first page.
library(shiny)
runApp(shinyApp(
ui = fluidPage(
title = "minimal-working-example",
fluidRow(
column(3, inputPanel(
selectInput("field", "Field", choices = names(mtcars)),
numericInput("value", "Value", 0),
actionButton("submit", "Submit")
)),
column(9,
DT::dataTableOutput("table")
)
)
),
server = function(input, output) {
v <- reactiveValues(mtcars=mtcars)
observeEvent(input$submit, {
v$mtcars[input$field] <- input$value
})
output$table <- DT::renderDataTable({
DT::datatable(
v$mtcars,
selection = "single",
options = list(pageLength = 5))
})
}
))
Session Info:
Session info --------------------------
setting value
version R version 3.3.0 (2016-05-03)
system x86_64, mingw32
ui RStudio (0.99.902)
language (EN)
collate English_United States.1252
tz America/Chicago
date 2016-07-11
Packages -------------------------------
package * version date source
DT 0.1.45 2016-02-09 Github (rstudio/DT@a63e9ac)
shiny * 0.13.0.9000 2016-02-08 Github (rstudio/shiny@e871934)
答案 0 :(得分:7)
这可以从R内部完成,而不通过JS进入datatable
的结构或类似的东西。
我们利用从DT
包中获取的各种表状态信息来呈现新的更新datatable
,就像之前一样。我们使用的所有内容都在this DT
documentation中描述。
第一项:选择。您可以通过在数据表的selected = ...
参数内添加selection
来预先选择行。这可以与变量input$table_rows_selected
组合以保存先前选择的行,并在重新渲染时预先选择该确切的行。
第二项:Page。 datatable
包有一个选项displayStart
,用于指定在呈现表时应首先显示哪一行。 Documentation here.因此,如果每页有5行,displayStart = 9
将在第3页开始显示。(JavaScript数组从0开始,因此总是减1)。这可以与{{1}结合使用这是当前可见行号的向量。如果我们存储第一个条目(减1),我们知道从哪里开始显示。
下面的完整代码示例:
input$table_rows_current