简体   繁体   English

如何通过从 UI 中选择的变量反应性地聚合数据?

[英]How to aggregate data reactively with shiny by the variables you selected from UI?

I am working on an R shiny app and trying to aggregate data by group sum based on the variable I selected from UI.我正在开发一个 R 闪亮的应用程序,并尝试根据我从 UI 中选择的变量按组总和聚合数据。 The following is my raw data:以下是我的原始数据:

Date        Month    Site   enrollment
3/30/2020   2020-03  14     1
4/6/2020    2020-04  14     21
4/13/2020   2020-04  14     8
4/20/2020   2020-04  14     8
4/27/2020   2020-04  14     13
5/4/2020    2020-05  14     18
5/11/2020   2020-05  14     19
5/18/2020   2020-05  14     13

I want to aggregate data by group sum.我想按组总和聚合数据。

Month   Site    enrollment
2020-03     14   1
2020-04     14  50
2020-05     14  35

I try to create a reactive data by code below:我尝试通过以下代码创建反应数据:

raw<-subset(aggregate(get(input$ycol) ~ get(input$xcol)+get(input$fill),df, sum),get(input$ycol)!=0);

Unfortunately, R shiny do not recognize get(input$ycol) .不幸的是,R 闪亮不承认get(input$ycol) If I change it to the variable name I choose (eg site, enrollment), then it works well.如果我将其更改为我选择的变量名称(例如站点、注册),那么它运行良好。

Following is my shiny code.以下是我闪亮的代码。

library(dplyr)

# Define UI for overall application
ui <- fluidPage(
  
  # Application title
  titlePanel("Data Visualization  -- Clinical Study Enrollment"),
  
  tabsetPanel(
    # Data upload tab
    tabPanel("Upload File",
             titlePanel("Upload CSV File"),
             
             # sidebar layout with input and output definitions--
             sidebarLayout(
               
               # sidebar panel for inputs --- 
               sidebarPanel(
                 
                 # input-- select file
                 fileInput('file_input',
                           'Choose CSV(UTF-8) File',
                           multiple = FALSE,
                           accept = c('text/csv',
                                      'text/comma-separated-values,text/plain',
                                      '.csv')),
                 
                 # Horizontal line ----
                 tags$hr(),
                 
                 checkboxInput('header', 'Header', TRUE),
                 
                 radioButtons('sep',
                              'Separator',
                              c(Comma=',',
                                Semicolon=';',
                                Tab='\t'),
                              ','),
                 
                 radioButtons('quote',
                              'Quote',
                              c(None='',
                                'Double Quote'='"',
                                'Single Quote'="'"),
                              '"'),
                 tags$hr(),
                 
                 # Input: Select number of rows to display ----
                 radioButtons("disp", "Display",
                              choices = c(Head = "head",
                                          All = "all"),
                              selected = "head")
               ),
               
               # main panel to display outputs
               mainPanel(
                 # output-- data file
                 DT::dataTableOutput('contents')
               )
             )
    ),
    
    # point estimate line plot
    tabPanel("Clinical study enrollment Plot",
             pageWithSidebar(
               headerPanel('Clinical study enrollment Plot'),
               
               sidebarPanel(
                 # drop down menu inputs
                 selectInput('xcol', 'Select X', ""),
                 
                 selectInput('ycol', 'Select Y', ""),
                 
                 selectInput('fill', 'Group', ""),
                 
              
               ),
               
               mainPanel(
                
                 DT::dataTableOutput('lineplot_table'))
             )
             
    )))


server <- function(input, output, session) {
  # Read upload file
  upload_data <- reactive({
 
    
    req(input$file_input);
    
    tryCatch({
      df <- read.csv(input$file_input$datapath,
                     header = input$header,
                     sep = input$sep,
                     quote = input$quote,
                     stringsAsFactors = FALSE,check.names=FALSE,fileEncoding = "UTF-8-BOM");
    }, error = function(e) {
      stop(safeError(e));
    })
    
    
    return(df);
  })
  
  
  # Display
  display_data <- reactive({
    df <- upload_data();
    
    if(input$disp == "head") {
      return(head(df));
    } else {
      return(df);
    }
  })
  
  observe({
    df <- upload_data();
    updateSelectInput(session, inputId = 'xcol',
                      label = 'Select X',
                      choices = names(df), selected = "Site");
    updateSelectInput(session, inputId = 'ycol',
                      label = 'Select Y',
                      choices = names(df), selected = "enrollment");
    updateSelectInput(session, inputId = 'fill',
                      label = 'Group',
                      choices = names(df), selected = "Date");
    
  })
  
  # Get bar plot data
  get_barplot_data <- reactive({
    
    df <- upload_data();
   
    raw<-subset(aggregate(get(input$ycol) ~ get(input$xcol)+get(input$fill),df, sum),get(input$ycol)!=0);
    
    return(raw)
  })
  
  
 
  # Display data you uploaded
  output$contents <- DT::renderDataTable({
    display_data();
  })
  
  output$lineplot_table <- DT::renderDataTable({
    get_barplot_data();
    
  })
  
 
  
}

shinyApp(ui = ui, server = server)

Try use as.formula or reformulate in this case, to build your formula.尝试使用as.formulareformulate在这种情况下,建立自己的公式。 This will allow you to use character values from shiny input in creating a formula for aggregate .这将允许您在创建aggregate公式时使用来自闪亮input字符值。

For example:例如:

raw <- subset(
  aggregate(
    reformulate(
      response = input$ycol,
      termlabels = c(input$xcol, input$fill)
    ),
    df,
    FUN = sum
  ),
  get(input$ycol) != 0
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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