使用 trycatch 块读取 csv 和 excel 文件
using a trycatch block to read a csv and an excel file
我试图在一个函数中同时提供上传 csv 和 excel sheet 的选项。我正在使用 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)
})
})
我认为实际上最好执行 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")
我试图在一个函数中同时提供上传 csv 和 excel sheet 的选项。我正在使用 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)
})
})
我认为实际上最好执行 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")