首页 > 解决方案 > RShiny中renderDataTable的求和列,并将结果存储在数据框中供以后使用

问题描述

不确定我是否在这里采用了正确的方法,但我创建了一个按预期工作的 Shiny 应用程序。当用户点击执行按钮时,它从源获取数据并将其显示为图表和表格。

下面的代表代码。为简单起见,删除了一些功能。

library(shiny)

ui <- fluidPage(

  actionButton("exe", "Run", 
               style="color: #fff; background-color: #337ab7; border-color: #2e6da4"),



  mainPanel(

    DT::dataTableOutput("datatable"),

  ))


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

  ga_data <- eventReactive( input$exe, {

    the_date <- as.Date(c('2020-03-01','2020-03-02','2020-03-03','2020-03-04','2020-03-05' ))
    users <- c(346, 223, 167, 431, 293)
    employ.data <- data.frame(the_date, users)

  })

  output$datatable <- DT::renderDataTable({
    req(ga_data())
    ga_data <- ga_data()



    })



  }

  shinyApp(ui = ui, server = server)

然而,我实际上想要做的是获取“用户”列的总和并将该单个值(1460)存储在其自己的变量或数据框中,以供以后在代码中使用(例如,作为计算转换率的分母)和让用户看不到表格。

任何帮助表示赞赏。

标签: rshinyshiny-reactivity

解决方案


当然,我们可以存储“用户”列的总和,而不是让表格可见。注意 的使用<<-,它确保值在任何地方都可用,而不仅仅是在它创建的地方。

library(shiny)

ui <- fluidPage(

  actionButton("exe", "Run", style="color: #fff; background-color: #337ab7; border-color: #2e6da4"),

  mainPanel(plotOutput('myplot'))

)

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

    ga_data <- eventReactive(input$exe, {

        the_date <- as.Date(c('2020-03-01', '2020-03-02', '2020-03-03', '2020-03-04', '2020-03-05'))
        users <- c(346, 223, 167, 431, 293)
        employ.data <- data.frame(the_date, users)

        #Store the sum of the column 'users' in a global variable, so we can use it anywhere later
        employ.data.sum <<- sum(employ.data$users, na.rm = TRUE)
        showNotification(paste("The sum of the column 'users' has been stored and is ready to use anywhere. Its", employ.data.sum))

        employ.data

    })

    output$myplot <- renderPlot({
        req(ga_data())
        plot(employ.data)
    })

}

shinyApp(ui = ui, server = server)

推荐阅读