Загрузите CSV-файл с помощью кнопки action и отобразите corpplot

Я пытался создать веб-приложение с R:: блестящим, но столкнулся с проблемой с фрагментом кода. Действительно, я хотел бы загрузить CSV-файл и отобразить коррелограмму.

Я попытался настроить коррелограмму с помощью actionbutton(), за которой следует updateSelectizeInput()

Однако произошла ошибка:

Ошибка: неподдерживаемый тип индекса: NULL

У кого-нибудь есть решение? Спасибо

NB - я не хочу использовать виджет fileInput для загрузки файла CSV! Только кнопкой действия!

library(shiny)
library(readr)
library(corrplot)
library(DT)


# File used for the example
data(iris)
write.csv(x = iris, file = "iris.csv")


#UI
ui <- shinyUI(
  fluidPage(
    navbarPage(
      id = "navbar",
      tabPanel(
        title = "UPLOAD",
        br(),
        actionButton(inputId = "file", label = "ADD A FILE")
      )
    )
  )
)

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

  path <- reactiveValues(pth = NULL)

  file.choose2 <- function(...) {
    pathname <- NULL;
    tryCatch({
      pathname <- file.choose();
    }, error = function(ex) {
    })
    pathname;
  }

  observeEvent(input$file,{
    path$pth <- file.choose2()
  })

  observeEvent(input$file,  {
    newvalue <- "B"
    updateNavbarPage(session, "navbar", newvalue)
  })

  data <- reactive({
        df <- readr::read_csv(file = path$pth)
        return(df)
  })

  observeEvent(input$file,  {
    appendTab(
      inputId = "navbar",
      tabPanel(
        value = "B",
        title = "Corr",
        sidebarLayout(
          sidebarPanel(
            selectizeInput(
              inputId = "select04",
              label = "Select features",
              choices = NULL,
              multiple = TRUE)
          ),
          mainPanel(
            plotOutput(
              outputId = "corrplot01", height = "650px")
          )
        )
      )
    )
  }, once = TRUE)

  # I suppose there is a problem with this line
  observeEvent(input$select04, { 
    col <- names(data())
    col.num <- which(sapply(data(), class) == "numeric")
    col <- col[col.num]
    updateSelectizeInput(session = session, inputId = "select04", choices = col)
  })

  output$corrplot01 <- renderPlot({ 
    df <- data()
    df1 <- df[,input$select04]
    corr <- cor(x = df1, use  = "pairwise.complete.obs")
    corrplot(corr = corr, 
             title = "")
  })
}

shinyApp(ui, server)

1 ответ

Решение

Я немного изменил ваш интерфейс и сервер, но думаю, что это может решить вашу проблему.

Я удалил observeEvent(input$file, ...{}) с сервера и добавил часть пользовательского интерфейса непосредственно в пользовательский интерфейс.

Я также добавил 3 req() звонки в data реактивный, во втором observeEvent(input$select04, ...{}) который я изменил на нормальный observe и в renderPlot вызов.

library(shiny)
library(readr)
library(corrplot)
library(DT)


# File used for the example
data(iris)
write.csv(x = iris, file = "iris.csv", row.names = F)


#UI
ui <- shinyUI(
  fluidPage(
    navbarPage(
      id = "navbar",
      tabPanel(
        title = "UPLOAD",
        br(),
        actionButton(inputId = "file", label = "ADD A FILE"),
        tabPanel(
          value = "B",
          title = "Corr",
          sidebarLayout(
            sidebarPanel(
              selectizeInput(width = "300px",
                inputId = "select04",
                label = "Select features",
                choices = NULL,
                multiple = TRUE)
            ),
            mainPanel(
              plotOutput(
                outputId = "corrplot01", height = "650px")
            )
          )
        )
      )
    )
  )
)

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

  path <- reactiveValues(pth = NULL)

  file.choose2 <- function(...) {
    pathname <- NULL;
    tryCatch({
      pathname <- file.choose();
    }, error = function(ex) {
    })
    pathname;
  }

  observeEvent(input$file,{
    path$pth <- file.choose2()
  })

  observeEvent(input$file,  {
    newvalue <- "B"
    updateNavbarPage(session, "navbar", newvalue)
  })

  data <- reactive({
    req(path$pth)
    df <- readr::read_csv(file = path$pth)
    return(df)
  })


  # I suppose there is a problem with this line
  observe({ 
    req(names(data()))
    col <- names(data())
    col.num <- which(sapply(data(), class) == "numeric")
    col <- col[col.num]
    updateSelectizeInput(session = session, inputId = "select04", choices = col)
  })

  output$corrplot01 <- renderPlot({ 
    req(input$select04)
    df <- data()
    df1 <- df[,input$select04]
    corr <- cor(x = df1, use  = "pairwise.complete.obs")
    corrplot(corr = corr, 
             title = "")
  })
}

shinyApp(ui, server)
Другие вопросы по тегам