代码之家  ›  专栏  ›  技术社区  ›  TarJae

csv文件在r Shining应用程序启动时上载(准占位符文件)

  •  2
  • TarJae  · 技术社区  · 4 年前

    有了这段代码,我可以在我闪亮的应用程序中上传一个csv文件。

    library(shiny)
    
    ui <- fluidPage(
      sidebarLayout(
        sidebarPanel(
          fileInput("file1", "Choose CSV File", accept = ".csv"),
          checkboxInput("header", "Header", TRUE)
        ),
        mainPanel(
          tableOutput("contents")
        )
      )
    )
    
    server <- function(input, output) {
      output$contents <- renderTable({
        file <- input$file1
        ext <- tools::file_ext(file$datapath)
        
        req(file)
        validate(need(ext == "csv", "Please upload a csv file"))
        
        read.csv(file$datapath, header = input$header)
      })
    }
    
    shinyApp(ui, server)
    

    我想加载一个占位符csv文件 df.csv 在我闪亮的应用程序启动时自动启动。

    我认为这是可能的,还是我必须重新考虑我的策略?

    1 回复  |  直到 4 年前
        1
  •  2
  •   akrun    4 年前

    server ,我们可以使用 if/else 创建占位符的步骤 .csv 装载时

    server <- function(input, output) {
      output$contents <- renderTable({
        
        if(is.null(input$file1)) {
          
           dat <- read.csv(file.path(getwd(), "df.csv"))
        } else {
        file <- input$file1
        ext <- tools::file_ext(file$datapath)
        
        req(file)
          validate(need(ext == "csv", "Please upload a csv file"))
        
        dat <- read.csv(file$datapath, header = input$header)
        }
        
        dat
        
        })
    }
    
    shinyApp(ui, server)