简体   繁体   中英

Calculating cumulative values from selected rows in DT

I want to be able to select several rows from at a DT and have a cumulative percentage of a column value represented in a flexdashboard gauge. I need to call from the selected rows as I'm planning to use this with crosstalk , where rows will be selected from scatter plots or maps.

This toy example allows me to produce a DT where I can click on rows 2-10 and the printed selectedRow() will show me the cumulative sum of the Petal.width column, and the gauge will render the sum exactly how I want it.

library(shiny)
library(DT)
library(flexdashboard)
shinyApp(
  ui = fluidPage(
    textOutput('list'),
    DTOutput('table'),
    flexdashboard::gaugeOutput("plt1")
  ),
  server = function(input, output, session) {

    iris2<-iris %>% mutate(perc=round((Petal.Width/sum(Petal.Width))*100,1))

    selectedRow <- eventReactive(input$table_rows_selected,{
      selrow<-cumsum(iris2$perc)[c(input$table_rows_selected)]
      tail(selrow, n=1)
    })

    output$plt1 <- flexdashboard::renderGauge({
      gauge(selectedRow(), min = 0, max = 100, symbol = '%', gaugeSectors(
        success = c(80, 100), warning = c(40, 79), danger = c(0, 39)))
    })

    output$list<-renderText({
      selectedRow()
    })

    output$table <- renderDT({iris2})

  }
)

ui <- fluidPage(
  mainPanel(
    verbatimTextOutput('list'),
    dataTableOutput('table')
  )
)

However, if I select rows 2-10, and then select the first row, the gauge resets to the value present in only the first row. I looked over the DT documentation and couldn't find any obvious way to change this, so I tried to select only the tail of the cumsum value in selectedRow() but this hasn't worked.

Is there any way to get the reactively selected cumulative sum of Petal.width, regardless of the order in which the DT rows are selected?

Using sum() instead of cumsum() seems to work for me.

library(shiny)
library(DT)
library(tidyverse)
library(flexdashboard)
shinyApp(
 ui = fluidPage(
textOutput('list'),
DTOutput('table'),
flexdashboard::gaugeOutput("plt1")
),
server = function(input, output, session) {

iris2<-iris %>% mutate(perc=round((Petal.Width/sum(Petal.Width))*100,1))

selectedRow <- eventReactive(input$table_rows_selected,{
  selrow<-sum(iris2$perc[c(input$table_rows_selected)])

})

output$plt1 <- flexdashboard::renderGauge({
  gauge(selectedRow(), min = 0, max = 100, symbol = '%', gaugeSectors(
    success = c(80, 100), warning = c(40, 79), danger = c(0, 39)))
})

output$list<-renderText({
  selectedRow()
})

output$table <- renderDT({iris2})

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM