首页 > 解决方案 > R Shiny - 在服务器加载时加载 csv 文件

问题描述

我想让我的 server.R 文件在启动时加载二进制矩阵的 csv 文件。

      library(shiny)


server <- function(input, output) {

  #this aint loading 
  df <- read.csv("starGraphAdjMatrix.csv",
                 header = TRUE,
                 sep = ",",
                 quote='"')


  #output$loadedMat -> output$loadedMat
  output$loadedMat <- renderTable({

    # input$file1 will be NULL initially. After the user selects
    # and uploads a file, head of that data file by default,
    # or all rows if selected, will be shown.

    #falsy value if empty
    req(input$file1)

    # when reading semicolon separated files,
    # having a comma separator causes `read.csv` to error
    tryCatch(
      {
        df <- read.csv(input$file1$datapath,
                       header = TRUE,
                       sep = ",",
                       quote='"')

        df$X <- NULL

      },
      error = function(e) {
        # return a safeError if a parsing error occurs
        stop(safeError(e))
      }
    )

    return(df)

  },
  rownames = FALSE, colnames = FALSE)

}

包含 ui.R 和 starGraphAdjMatrix 的完整代码在这里: https ://github.com/andandandand/fixCSVLoad

标签: rshiny

解决方案


不确定这是否是您所追求的:

library(shiny)

server <- function(input, output) {

  output$contents <- renderTable({

    if (is.null(input$file1$datapath)) {
      dpath <- "starGraphAdjMatrix.csv"
    } else {
      dpath <- input$file1$datapath
    }

    read.csv(dpath)
  }, rownames = FALSE, colnames = FALSE)
}

推荐阅读