【问题标题】:using a trycatch block to read a csv and an excel file使用 trycatch 块读取 csv 和 excel 文件
【发布时间】:2015-05-11 20:28:43
【问题描述】:

我试图在一个函数中同时提供上传 csv 和 excel 表的选项。我正在使用 read.csv 从 XLConnect 包中读取 csv 文件和 readworksheetfromfile 来读取 excel 文件。我为此使用了 trycatch 块,但是当 csv 文件通过 readworksheetfromfile 函数传递时,我仍然收到错误。我的 tryblock 看起来像

filedata <- reactive({
infile <- input$templatedfile
if (is.null(infile)) {
  # User has not uploaded a file yet
  return(NULL)
} 

importedfile = tryCatch({
  read.csv(infile$datapath,stringsAsFactors=FALSE)
},  finally = {
  readWorksheetFromFile(infile$datapath,sheet=1,check.names=FALSE)
})
})

【问题讨论】:

  • 您收到什么错误?
  • 您可能会考虑使用 rio 来自适应地读取各种文件格式(它使用 readxl 而不是 XLConnect 来导入 Excel 文件):cran.r-project.org/web/packages/rio
  • @Thomas,rio 是否解决了当前readxlshiny 有关文件名的问题?见问题here
  • 我没试过,但应该可以。

标签: r excel csv shiny shiny-server


【解决方案1】:

我认为您实际上最好执行switch 语句。这样,您就不会浪费计算时间来尝试将文件作为 csv 读取,而实际上它不是。如果有人上传的文件既不是 csv 文件也不是 excel 文件,您可能还需要一个后备选项。这是您的filedata 函数的实现。

filedata <- reactive({
    infile <- input$templatedfile
    if(is.null(infile)){
        return(NULL)
    }
    ext <- file_ext(infile$name)

    importedfile <- 
        switch(ext,
               csv = read.csv(infile$datapath, stringsAsFactors=FALSE),
               xlsx = , xls = readWorksheetFromFile(infile$datapath,
                                                    sheet=1,
                                                    check.names=FALSE),
               stop("file extension not recognized"))
})

这是一个简单的要点,我用来验证它是否正常工作。

runGist("https://gist.github.com/cdeterman/a41cceadffa7907c505e")

【讨论】:

    猜你喜欢
    • 2018-09-07
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    • 2017-09-26
    • 2019-04-09
    • 2019-04-13
    • 2020-06-12
    • 2013-05-06
    相关资源
    最近更新 更多