首页 > 解决方案 > 当文件存在但可以读取时,如何使用 read_excel 进行错误处理?

问题描述

当文件存在时,有没有办法使用 R 中的函数“read_excel”进行错误处理,但由于其他原因(例如,格式错误或其他原因)无法读取它?

只是为了说明,我的一段代码如下:

f <- GET(url, authenticate(":", ":", type="ntlm"), write_disk(tf <- tempfile(tmpdir = here("data/temp"), fileext = ".xlsx")))
dt <- read_excel(tf)

其中 url 包含 http 文件地址。

我想检查 read_excel 是否返回错误以进行正确处理并防止降价停止。

提前致谢!

标签: r

解决方案


看起来像一个重复的问题。下面的代码是根据此处找到的答案修改的。下面代码中的someOtherFunction是在出现错误时可以运行某些函数的地方。

f <- GET(url, authenticate(":", ":", type="ntlm"), write_disk(tf <- tempfile(tmpdir = here("data/temp"), fileext = ".xlsx")))

t <- try(read_excel(tf))

if("try-error" %in% class(t)) SomeOtherFunction()

推荐阅读