如何在上传另一数据时从闪亮中删除一个数据

问题描述 投票:0回答:1

为了通过最小的示例来说明我的问题,让我们考虑下面的代码(作为完全可重现的示例)。

library(shiny)

ui <- fluidPage(
  fileInput("upload", NULL, accept = c(".csv", ".tsv")),
  numericInput("n", "Rows", value = 5, min = 1, step = 1),
  tableOutput("head"),
  fileInput("upload2", NULL, accept = c(".csv", ".tsv")),
  numericInput("n2", "Rows", value = 5, min = 1, step = 1),
  tableOutput("head2")
)

server <- function(input, output, session) {
  data <- reactive({
    req(input$upload)
    
    ext <- tools::file_ext(input$upload$name)
    switch(ext,
           csv = vroom::vroom(input$upload$datapath, delim = ","),
           tsv = vroom::vroom(input$upload$datapath, delim = "\t"),
           validate("Invalid file; Please upload a .csv or .tsv file")
    )
  })
  
  output$head <- renderTable({
    head(data(), input$n)
  })
  
  data2 <- reactive({
    
    req(input$upload2)
    
    ext <- tools::file_ext(input$upload2$name)
    switch(ext,
           csv = vroom::vroom(input$upload2$datapath, delim = ","),
           tsv = vroom::vroom(input$upload2$datapath, delim = "\t"),
           validate("Invalid file; Please upload a .csv or .tsv file")
    )
  })
  
  output$head2 <- renderTable({
    head(data2(), input$n2)
  })
  
}

shinyApp(ui, server)

应用程序要求用户上传数据集,然后询问行数并显示上传数据的

head()
。还有一个类似的界面。

现在我的要求是,每当闪亮的应用程序用户上传

data2
时,应将
data
从环境中删除,并且摘要也应删除;如果显示
data2
信息,则数据反之亦然。

我尝试了很多方法,例如使用

observeEvent
eventReactive
等,但我无法做到。请推荐。

r shiny upload reactive-programming
1个回答
0
投票

试试这个

library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  fileInput("upload", NULL, accept = c(".csv", ".tsv")),
  numericInput("n", "Rows", value = 5, min = 1, step = 1),
  tableOutput("head"),
  fileInput("upload2", NULL, accept = c(".csv", ".tsv")),
  numericInput("n2", "Rows", value = 5, min = 1, step = 1),
  tableOutput("head2")
)

server <- function(input, output, session) {
  data <- reactive({
    req(input$upload)
    
    ext <- tools::file_ext(input$upload$name)
    switch(ext,
           csv = vroom::vroom(input$upload$datapath, delim = ","),
           tsv = vroom::vroom(input$upload$datapath, delim = "\t"),
           validate("Invalid file; Please upload a .csv or .tsv file")
    )
  })
  
  output$head <- renderTable({
    head(data(), input$n)
  })
  
  data2 <- reactive({
    
    req(input$upload2)
    
    ext <- tools::file_ext(input$upload2$name)
    switch(ext,
           csv = vroom::vroom(input$upload2$datapath, delim = ","),
           tsv = vroom::vroom(input$upload2$datapath, delim = "\t"),
           validate("Invalid file; Please upload a .csv or .tsv file")
    )
  })
  
  observeEvent(input$upload, {
    shinyjs::hide("head2")
    shinyjs::show("head")
  })

  observeEvent(input$upload2, {
    shinyjs::hide("head")
    shinyjs::show("head2")
  })
  
  output$head2 <- renderTable({
    head(data2(), input$n2)
  })
  
}

shinyApp(ui, server)
© www.soinside.com 2019 - 2024. All rights reserved.