将可反应的 R 包与 Shiny 一起使用,如何以编程方式排序? 如果用户已按其他列排序,我希望能够通过单击按钮返回到默认排序顺序。 这是因为用于排序的列对用户来说是不可见的。
这是一个最小的例子
library(shiny)
library(reactable)
ui <- fluidPage(
reactableOutput("table")
, actionButton("sort_button", "default sort")
)
server <- function(input, output) {
output$table <- renderReactable({
reactable(
iris
, columns = list(
Sepal.Length = colDef(show = FALSE))
, sortable = TRUE
, defaultSorted = list(Sepal.Length = "asc")
)
})
}
shinyApp(ui, server)
您基本上想要的是表刷新。只有当数据是反应性的并且发生变化时,才会发生这种情况。那么如何在不实际更改数据的情况下更改数据呢?一种选择是稍微增加一个值。另一个是添加虚拟记录。这个技巧/黑客/解决方法可能在某些情况下有效。
library(shiny); library(dplyr)
library(reactable)
runApp( list(
ui = fluidPage(
reactableOutput("table")
, actionButton("sort_button", "default sort")
),
server = function(input, output) {
r <- reactiveValues( iris2 = iris )
output$table <- renderReactable({
reactable(
r$iris2
, columns = list(
Sepal.Length = colDef(show = FALSE))
, sortable = TRUE
, defaultSorted = list(Sepal.Length = "asc")
)
})
observeEvent(input$sort_button, {
# update/restore value on each click
if (nrow(r$iris2[with(r$iris2, which(Species=='setosa' & Sepal.Length==4.7 & Sepal.Width==3.2 & Petal.Length==1.3 & Petal.Width==0.2)),])>0)
r$iris2 <- r$iris2 %>% mutate(Petal.Length = replace(Petal.Length, which(Species=='setosa' & Sepal.Length==4.7 & Sepal.Width==3.2 & Petal.Length==1.3 & Petal.Width==0.2), 1.301))
else
r$iris2 <- r$iris2 %>% mutate(Petal.Length = replace(Petal.Length, which(Species=='setosa' & Sepal.Length==4.7 & Sepal.Width==3.2 & Petal.Length==1.301 & Petal.Width==0.2), 1.3))
})
}
))