在闪亮的应用程序中使用操作按钮移动到数据帧的下一行

Use actionbutton to move to the next row of dataframe in a shiny app

我有下面的 shiny 应用程序,当用户点击数据表的一行时,另一个数据框中会出现一个子集 df 并显示一个文本。

我想在按下 Next actionbutton() 文本时显示子集数据帧的下一行数据。在这种情况下,它应该显示 "flower b has score 5".

我的原始数据会有很多行,所以每次按 Next 时,我需要根据对应的行调整文本。

shinyApp(
  ui = fluidPage(DT::dataTableOutput('tableId'),
                 textOutput("celltext"),
                 actionButton("next","Next")),
  server = function(input, output) {
    output$tableId = DT::renderDataTable(
      iris[,c(1,5)],  selection = list(target = 'row',mode="single")
    )
    species<-c("setosa","setosa","virginica","virginica")
    flower<-c("a","b","c","d")
    score<-c(7,5,6,9)
    df<-data.frame(species,flower,score)
    
    observeEvent(input$tableId_rows_selected, {
    output$celltext <- renderText({
      cell <- input$tableId_rows_selected
      dat<-df[df$species %in% iris[cell,5],]
      df <-dat[order(dat$score,decreasing = T),]
      df
      paste("flower",df[1,2],"has score",df[1,3])
    })
    })
  }
)

定义 reactiveValues 对象会有帮助。也许你正在寻找这个

shinyApp(
  ui <- fluidPage(DT::dataTableOutput('tableId'),
                 textOutput("celltext"),
                 actionButton("next","Next")),

  server <- function(input, output) {
    rv <- reactiveValues(text=NULL)
    dt <- reactiveValues(data=NULL)
    rnum <- reactiveVal(0)
    output$tableId = DT::renderDataTable(
      iris[,c(1,5)],  selection = list(target = 'row',mode="single")
    )
    species<-c("setosa","setosa","virginica","virginica","setosa","setosa","virginica","virginica")
    flower<-c("a","b","c","d","e","f","g","h")
    score<-c(7,5,6,9,1,2,3,4)
    df<-data.frame(species,flower,score)

    observeEvent(input$tableId_rows_selected, {
      row <- input$tableId_rows_selected
      dat<-df[df$species %in% iris[row,5],]
      dt$data <-dat[order(dat$score,decreasing = T),]
      rv$text <- paste("flower",dt$data[1,2],"has score",dt$data[1,3])
      rnum(1)
      output$celltext <- renderText({
        rv$text
      })

    })

    observeEvent(input[['next']], {
      rnum(rnum()+1)
      rv$text <- paste("flower",dt$data[rnum(),2],"has score",dt$data[rnum(),3])
    })
  }
)