简体   繁体   中英

R Shiny Summary Statistics from selected drop down variable

I am very new to R shiny. I have been developing a code that will allow me to select variable from a .csv dataset and then produce summary statistics. The drop down menu to select variable is not getting activated, the previous functionality to filter the data based on strata is not working and the summary statistics is not getting generated. Any help will be greatly appreciated. Thank you.

library(shiny)
library(ggplot2)
library(dplyr)
library(tidyverse)


## Only run examples in interactive R sessions
if (interactive()) {

  ui <- fluidPage(

    # App title ----
    titlePanel("Survey Data Analysis Template"),

    # Sidebar layout with input and output definitions ----
    sidebarLayout(

      # Sidebar panel for inputs ----
      sidebarPanel(

        # Input: Select a file ----
        fileInput("file1", "Choose CSV File",
                  multiple = TRUE,
                  accept = c("text/csv",
                             "text/comma-separated-values,text/plain",
                             ".csv")),

        # Horizontal line ----
        tags$hr(),

        # Input: Checkbox if file has header ----
        checkboxInput("header", "Header", TRUE),

        # Input: Select separator ----
        radioButtons("sep", "Separator",
                     choices = c(Comma = ",",
                                 Semicolon = ";",
                                 Tab = "\t"),
                     selected = ","),

        # Input: Select quotes ----
        radioButtons("quote", "Quote",
                     choices = c(None = "",
                                 "Double Quote" = '"',
                                 "Single Quote" = "'"),
                     selected = '"'),

        # Horizontal line ----
        tags$hr(),

        # Input: Select number of rows to display ----
        radioButtons("disp", "Display",
                     choices = c(Head = "head",
                                 All = "all"),
                     selected = "head"),



        # Include a Slider for Strata
        sliderInput("strata",
                    "strata:",
                    min = 1,
                    max = 20,
                    value = c(1,20),
                    step=1),

      # Select Variable from the selected Dataset 


      selectInput("vari", "Variable", 
                   choices=colnames(df)),

       hr(),
       helpText("")  


      ),  

      ########################## 

      # Main panel for displaying outputs ----
      mainPanel(

        # Output: Data file ----
        tableOutput("contents"),
        verbatimTextOutput("summary") # Generate Summary Statistics for the selected variable by strata 

      )  
    )
  )






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

    mytable <- reactive({

      req(input$file1)

      df <- read.csv(input$file1$datapath,
                     header = input$header,
                     sep = input$sep,
                     quote = input$quote, stringsAsFactors = FALSE)

      print(df)
      df<-as.data.frame(df)

      # Subset the data to filter based on strata 
      df<- df %>% 
      filter(df$Strata>=input$strata[1] & df$Strata<=input$strata[2])



      df<-as.data.frame(df)
      print(df)

      if(input$disp == "head") {
        return(head(df))
      }
      else {
        return(df)
      }


    # Output by Strata Filter
    output$contents <- renderTable({
      # Now do use (), since we are calling a value from a reactive.
      mytable()


    })

    # Create Table of Summary Statistics from the selected Variable

    print(mytable)
    mytable<-as.data.frame(mytable)

    # Select based on the drop down variable
    mytable<- mytable %>% 
      select(mytable$vari)

    # Generate a summary of the dataset
    output$summary <- renderPrint({
      dataset <- mytable()
      summary(dataset)
    })


    })


  }
  # Run the app ----
  shinyApp(ui, server)

}

Sorry, but your code is a little messy hence I started scratch based on another answer and used that as the starting point. 在此处输入图片说明 The following code does a couple of things:

  1. Display the uploaded CSV,
  2. Display Summary of the CSV
  3. Plot histogram of the selected variable (if it's numeric).

Variable Dropdown is created with renderUI inside server

 library(shiny)
    library(DT)

    server <- function(input, output, session){
      myData <- reactive({
        inFile <- input$file1
        if (is.null(inFile)) return(NULL)
        data <- read.csv(inFile$datapath, header = TRUE)
        data
      })

      output$contents <- DT::renderDataTable({
        DT::datatable(myData())       
      })

      output$summary <- renderPrint({
          summary(myData())
      })

      output$select <- renderUI({
        df <- myData()
        selectInput("variable", "Variable:",names(df))


      })


      output$plot <- renderPlot({
        df <- myData()
        df <- df[,input$variable]
        hist(df)
      })

    }


    ui<- shinyUI(fluidPage(
      titlePanel("Uploading Files"),
      sidebarLayout(
        sidebarPanel(
          fileInput('file1', 'Choose CSV File',
                    accept=c('text/csv',
                             'text/comma-separated-values,text/plain',
                             '.csv')),
          uiOutput('select')
        ),
        mainPanel(
          DT::dataTableOutput('contents'),
          verbatimTextOutput('summary'),
          plotOutput('plot')
        )
      )
    )
    )

    shinyApp(ui,server)
mytable <- reactive({ 

doesn't have a matching }) in the correct place.

Also, this section:

# Create Table of Summary Statistics from the selected Variable

print(mytable)
mytable<-as.data.frame(mytable)

# Select based on the drop down variable
mytable<- mytable %>% 
  select(mytable$vari)

Isn't in any kind of reactive context. So it will never run. Also, you've written

mytable <- as.data.frame(mytable)

when you mean:

mytable <- as.data.frame(mytable())

I wouldn't do that either though. Call it something else:

newTable <- as.data.frame(mytable())

Fix all that and have another go.

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