Реактив, который получает имена из листа Excel для приложения Shiny, чтобы выбрать, какой столбец будет помещен в ggplot - PullRequest
0 голосов
/ 25 мая 2018

TL; DR, это мое первое приложение в Shiny, и я застрял на этой реактивной проблеме.

Я пишу приложение Shiny, которое будет принимать данные опросов Excel и помещать их в функцию ggplot.Функция должна работать, но вопросы опроса меняются от года к году.Я хочу, чтобы приложение выполняло следующие действия:

  1. Возьмите несколько файлов Excel и прочитайте их
  2. Отобразите три раскрывающихся меню для названия организации, количества добровольцев / часов и годаопрос был проведен, и отображены три формы ввода текста для меток X и Y и заголовка
  3. . Распечатать гистограмму, показывающую для каждой организации число добровольцев с уклоненными столбиками за каждый год, в котором организация появилась.

Проблема со вторым заданием.Я хочу, чтобы приложение реагировало на загрузку файлов, помещая весь список colnames () в раскрывающееся меню, чтобы пользователь мог выбрать, какие столбцы имели название организации.Я пробовал решения других вопросов по переполнению стека, но все они заканчивались ошибками.

Вот мой пользовательский интерфейс и код сервера:


library(rsconnect)
library(readxl)
library(shiny)
library(ggplot2)



dataset <- file

ui <- fluidPage(
  shinythemes::themeSelector(),
  titlePanel("Volunteer stats"),

  sidebarLayout(

    sidebarPanel(
      #I need: names of each of the files, 
      #   columns for org, num_vol, and survey year, 
      #   labels for x axis, y axis, and title, 
      #   name for the PDF to be created

    fileInput(inputId = "file", label = "Choose Excel file", multiple = TRUE),
    uiOutput("org_select"),
    uiOutput("num_select"),
    uiOutput("year_select"),
    textInput(inputId = "org_label", label = "X axis label"), 
    textInput(inputId = "vols_label", label = "Y axis label"), 
    textInput(inputId = "plot_title", label = "Chart title"),
    textInput(inputId = "pdf_title", label = "PDF title")), 

  mainPanel(
    plotOutput(
      outputId = "histogram"
  )
  )
))

server <- function(input, output) {

  output$org_select <- renderUI({
        selectInput("org_col", "Which column has the organization name?", choices = list(colnames(read_excel(input$file))), label = "Organization")
  })
  output$num_select <- renderUI({
    selectInput("num_vols", "Which column has the relevant metric?", choices = list(colnames(read_excel(input$file))), label = "Number of Volunteers")
  })
  output$year_select <- renderUI({
    selectInput("year", "Which column has the year?", choices = list(colnames(read_excel(input$file))), label = "Year")
  })

#assemble all the files into a list based on the input, to be passed to ggplot (not shown) 
  getData <- reactive({
    if (is.null(input$file)){
      return(NULL)
    }else{
      numfiles = nrow(input$file)
      files_list = list(
        for(i in 1:numfiles)
        {
          XL_file = read_excel(input$file[[i, 'datapath']], header = TRUE)
          lastrow = nrow(XL_file)
          shift = function(x, n){
            c(x[-(seq(n))], rep(NA, n)) 
          }
          XL_file$identity = shift(XL_file$identity, 1)
          files_list[[i]] = XL_file[-lastrow, ]
        }
      )
    }
  })
getData()
shinyApp(ui = ui, server = server)

Для краткости я не включил свою функцию ggplot.Если мне понадобится помощь, я задам отдельный вопрос позже.

Большое спасибо, Бесстрашный

1 Ответ

0 голосов
/ 25 мая 2018

Всего два небольших исправления, чтобы заставить его работать:

input$file - это объект (или список, если хотите), но read_excel() ожидает строку, содержащую путь к файлу.Используйте input$file$datapath.

Аргумент choices предполагает либо именованный список именованных, либо неназванных значений.С list(colnames(...)) вы передаете ему список с единственным элементом, содержащим выборы:

list(colnames(read_excel('path/to/file')))
[[1]]
[1] "COL_1"      "COL_2"             "COL_3"           "COL_4"   

Просто передайте ему colnames().

server <- function(input, output) {

  output$org_select <- renderUI({
    selectInput("org_col", "Which column has the organization name?", choices = colnames(read_excel(input$file$datapath)), label = "Organization")
  })
  output$num_select <- renderUI({
    selectInput("num_vols", "Which column has the relevant metric?", choices = colnames(read_excel(input$file$datapath)), label = "Number of Volunteers")
  })
  output$year_select <- renderUI({
    selectInput("year", "Which column has the year?", choices = colnames(read_excel(input$file$datapath)), label = "Year")
  })
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...