Кнопка Action перестает отображать данные при первой загрузке файла - PullRequest
0 голосов
/ 24 апреля 2020

У меня есть блестящее приложение ниже, в котором пользователь загружает CSV. Затем pickerInput получает уникальные значения первого столбца этого CSV и использует их для подмножества кадра данных и отображения его в таблице. Проблема в том, что я хочу использовать actionButton для применения изменений, но когда CSV загружается в первый раз, он должен отображаться полностью и не отображаться пустым, потому что actionButton еще не запущен. Для целей примера я использовал iris набор данных вместо CSV.

# app.R ##
library(shiny)
library(DT)
library(shinyWidgets)
ui <- pageWithSidebar(
  headerPanel('Iris k-means clustering'),
  sidebarPanel(
    fileInput("file1", "Choose CSV File",
              accept = c(
                "text/csv",
                "text/comma-separated-values,text/plain",
                ".csv")
    ),
    uiOutput("id"),

    actionButton("go","Go")
  ),
  mainPanel(
    uiOutput('contents')
  )
)

server <- function(input, output, session) {
  output$id<-renderUI({
    #inFile <- input$file1
    #df2<-data.frame(read.csv(inFile$datapath, header = TRUE))
    pickerInput("select", "Select ID", 
                choices = as.character(unique(iris$Species)), 
                multiple = T,options = list(`actions-box` = TRUE),
                selected = as.character(unique(iris$Species)))
  })
  output$contents <- renderUI({
    input$goButton
    #inFile <- input$file1
    #df<-data.frame(read.csv(inFile$datapath, header = TRUE))
    df<-data.frame(iris)
    df<-subset(iris,Species %in% isolate(input$select))

      renderDataTable({
        datatable(
          df,
          options = list(scrollX = TRUE,pageLength=5)
        )
        })

  })
}

shinyApp(ui = ui, server = server)

Ответы [ 2 ]

1 голос
/ 25 апреля 2020
library(shiny)
library(DT)
library(shinyWidgets)

ui <- pageWithSidebar(
  headerPanel('Iris k-means clustering'),
  sidebarPanel(
    fileInput("file1", "Choose CSV File",
              accept = c(
                "text/csv",
                "text/comma-separated-values,text/plain",
                ".csv")
    ),
    uiOutput("picker"),
    actionButton("go","Go")
  ),
  mainPanel(
    DTOutput("dtable")
  )
)

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

  filteredCSV <- reactiveVal(NULL)

  CSV <- eventReactive(input[["file1"]], {
    dat <- read.csv(input[["file1"]]$datapath, header = TRUE)
    filteredCSV(dat)
    dat
  })


  output[["picker"]] <- renderUI({
    req(CSV())
    choices <- unique(as.character(CSV()[,1]))
    pickerInput("select", "Select ID", 
                choices = choices, 
                multiple = TRUE, options = list(`actions-box` = TRUE),
                selected = choices)
  })

  observeEvent(input[["go"]], {
    req(CSV())
    filteredCSV(CSV()[CSV()[,1] %in% input[["select"]],])
  })

  output[["dtable"]] <- renderDT({
    req(filteredCSV())
    datatable(
      filteredCSV(), 
      options = list(scrollX = TRUE, pageLength = 5)      
    )
  })

}

shinyApp(ui = ui, server = server)
1 голос
/ 25 апреля 2020

Это ответ на предыдущую версию вашего поста, но он должен решить основную проблему - это то, как я бы go сказал об этом, используя реактивные выражения (и data.table, но вы также можете не использовать это):

library(shiny)
library(shinyWidgets)
library(DT)
library(data.table)

ui <- pageWithSidebar(
    headerPanel('Iris k-means clustering'),
    sidebarPanel(
        fileInput("file1", "Choose CSV File",
                  accept = c(
                      "text/csv",
                      "text/comma-separated-values,text/plain",
                      ".csv")
        ),
        uiOutput("id"),
        #actionButton("go","Go")
    ),
    mainPanel(
        DT::dataTableOutput('contents')
    )
)

server <- function(input, output, session) {
    getFile <- reactive({
        req(input$file1)
        fread(input$file1$datapath, header = TRUE)
    })

    output$contents <- DT::renderDataTable({
        DT::datatable(getFile()[get(colnames(getFile())[1]) %in% input$select])
    })

    output$id <- renderUI({
        req(getFile())
        df <- getFile()
        pickerInput("select", "Select ID", 
                    choices = unique(df[[1]]), 
                    multiple = TRUE, options = list(`actions-box` = TRUE),
                    selected = unique(df[[1]]))
    })
}

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