为什么输入$ tableid_all_rows(DT)在Shiny中工作?

问题描述 投票:1回答:1

我有以下应用程序:

...
              selectInput("cars", "Pick a Car: ",
                          c("All" = "All Cars",
                            "Ford" = "Ford",
                            "Volvo" = "Volvo",
                            "Ferrari" = "Ferrari",
                            "Fiat" = "Fiat",
                            "Merc" = "Merc"))
      )),

    shinySaveButton("save", "Save file", "Save file as ...", filetype=list(csv="csv")),
    DT::dataTableOutput('table1')
      )
    )

# Define server logic required to draw a histogram
server <- function(input, output, session) {

  mtcars$car <- rownames(mtcars)

  output$table1 <-renderDataTable({
    mtcars %>%
      filter(stringr::str_detect(car, as.character(input$cars)) | input$cars == 'All Cars')
    })

  observe({
    volumes <- c("UserFolder"="~/Documents/R1/DwnLdWord/saves")
    shinyFileSave(input, "save", roots=volumes, session=session)
    fileinfo <- parseSavePath(volumes, input$save)
    data <- input$table1_rows_all
    if (nrow(fileinfo) > 0) {
      write.csv(data, fileinfo$datapath)
    }
  })
}
# Run the application 
shinyApp(ui = ui, server = server)

当我保存静态数据集(如irismtcars)时,该文件会保存实际数据。但是,从图像中可以看出,我想保存过滤后的DT的内容。

我认为这就是input$tableid_rows_all的用途,但我只获得随机整数/数值。我总是遇到麻烦这个废话,但我真的想让它发挥作用,因为它是如此有价值的功能。

救命?

pic1 saving resulting

r shiny dt
1个回答
1
投票

检查一下:

server <- function(input, output, session) {

  mtcars$car <- rownames(mtcars)

  output$table1 <-renderDataTable({
    mtcars %>%
      filter(stringr::str_detect(car, as.character(input$cars)) | input$cars == 'All Cars')
    })

  observe({
    volumes <- c("UserFolder"="~/Documents/R1/DwnLdWord/saves")
    shinyFileSave(input, "save", roots=volumes, session=session)
    fileinfo <- parseSavePath(volumes, input$save)
     data <- mtcars[input$table1_rows_selected,]
    if (nrow(fileinfo) > 0) {
      write.csv(data, fileinfo$datapath)
    }
  })
}
# Run the application 
shinyApp(ui = ui, server = server)
  1. 你想使用rows_selectd因为rows_all在你的桌子上给你所有的rows
  2. 你需要用你的桌子名字(tableId)替换table1
  3. 你没有得到胡言乱语,但你选择的那些行的索引/行号(在你的情况下,所有)
  4. 要检索所有数据而不是行号,您需要mtcars[input$table1_rows_selected,]

我希望这能帮到你。最好!

© www.soinside.com 2019 - 2024. All rights reserved.