модульное приложение Shiny: модули CSV и Chart - PullRequest
1 голос
/ 13 января 2020

Я хочу создать модульное приложение Shiny, в котором один модуль, dataUpload, используется для импорта CSV, а другой модуль, chart, используется для

  1. Создание динамических элементов c выпадающие списки x и y на основе имен столбцов в CSV ЭТОГО РАБОТЫ
  2. Создание графика на основе выбранного входа $ xaxis, ввода $ yaxis Это приводит к ошибке недопустимого типа / длина (символ / 0) в распределении векторов

Я думаю, что проблема связана с моим реактивным ggplot в диаграмме. R , и я хотел бы любую помощь - я добавил вся информация здесь, но У меня также есть репозиторий github, если это проще Я думаю, что это может быть действительно отличная демонстрация в мире взаимодействующих модулей, поэтому я очень ценю любую помощь !!

App.R

library(shiny)
library(shinyjs)
library(tidyverse)

source("global.R")

ui <- 
  tagList(
    navbarPage(
      "TWO MODULES",
      tabPanel(
        title = "Data",
          dataUploadUI("datafile", "Import CSV")
      ),
      tabPanel(
        title = "Charts",
          chartUI("my_chart")
      )
    )
  )

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

  datafile <- callModule(dataUpload, "datafile", stringsAsFactors = FALSE)
  output$table <- renderTable({ datafile() })

  # PASS datafile WITHOUT () INTO THE MODULE 
  my_chart <- callModule(chart, "my_chart", datafile = datafile)
  output$plot <- renderPlot({ my_chart() })

}

shinyApp(ui, server)

dataUpload.R

dataUpload <- function(input, output, session, stringsAsFactors) {
  # The selected file, if any
  userFile <- reactive({
    # If no file is selected, don't do anything
    # input$file == ns("file")
    validate(need(input$file, message = FALSE))
    input$file
  })

  # The user's data, parsed into a data frame
  dataframe <- reactive({
    read.csv(userFile()$datapath,
             stringsAsFactors = stringsAsFactors)
  })

  # We can run observers in here if we want to
  observe({
    msg <- sprintf("File %s was uploaded", userFile()$name)
    cat(msg, "\n")
  })

  # Return the reactive that yields the data frame
  return(dataframe)

}

dataUploadUI.R

# The first argument is the id -- the namespace for the module
dataUploadUI <- function(id, label = "CSV file") {
  # Create a namespace function using the provided id
  #ALL UI FUNCTION BODIES MUST BEGIN WITH THIS
  ns <- NS(id)
  # Rather than fluidPage use a taglist
  # If you're just returning a div you can skip the taglist
  tagList(
  sidebarPanel(
    fileInput(ns("file"), label)),

  mainPanel(tableOutput("table"))
  )
}

chart.R

Я полагаю, что этот файл нуждается в незначительных изменениях для правильной визуализации графика?

chart <- function(input, output, session, datafile = reactive(NULL)) {

  # SINCE DATAFILE IS A REACTIVE WE ADD THE PRERENTHESIS HERE
  # WHERE/HOW CAN I ACCESS input$xaxis?
  # Do I need to use ns? Can you do that in the server side of a module?
  output$XAXIS <- renderUI(selectInput("xaxis", "X Axis", choices = colnames(datafile())))
  output$YAXIS <- renderUI(selectInput("yaxis", "Y Axis", choices = colnames(datafile())))

  # NOT WORKING
  # Use the selectInput x and y to plot
  p <- reactive({
    req(datafile)
    # WORKS: ggplot(datafile(), aes(x = Sepal_Length, y = Sepal_Width))
    # DOES NOT WORK:
    ggplot(datafile(), aes_(x = as.name(input$xaxis), y = as.name(input$yaxis))) +
      geom_point()
  })

  return(p)
}

chartUI.R

chartUI <- function(id, label = "Create Chart") {

  ns <- NS(id)
  tagList(
    sidebarPanel(
      uiOutput(ns("XAXIS")),
      uiOutput(ns("YAXIS"))
    ),
    mainPanel(plotOutput("plot"))
  )
}

1 Ответ

0 голосов
/ 14 января 2020

Нам нужно вручную указать пространство имен в функции renderUI, используя session$ns

chart <- function(input, output, session, datafile = reactive(NULL)) {

  # SINCE DATAFILE IS A REACTIVE WE ADD THE PRERENTHESIS HERE
  # WHERE/HOW CAN I ACCESS input$xaxis?
  # Do I need to use ns? Can you do that in the server side of a module?
  output$XAXIS <- renderUI(selectInput(session$ns("xaxis"), "X Axis", choices = colnames(datafile())))
  output$YAXIS <- renderUI(selectInput(session$ns("yaxis"), "Y Axis", choices = colnames(datafile())))

  # NOT WORKING
  # Use the selectInput x and y to plot
  p <- reactive({
    req(datafile)
    # WORKS: ggplot(datafile(), aes(x = Sepal_Length, y = Sepal_Width))
    # DOES NOT WORK:
    ggplot(datafile(), aes_(x = as.name(input$xaxis), y = as.name(input$yaxis))) +
      geom_point()
  })

  return(p)
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...