在R中读取xlsx文件时如何使用错误处理?
我正在尝试读取23个excel文件,将每个文件存储在一个列表中,然后将它们绑定到一个csv。这些文件中有些是csv文件,有些是xlsx文件。然而,我得到了以下信息:在R中读取xlsx文件时如何使用错误处理?,r,excel,R,Excel,我正在尝试读取23个excel文件,将每个文件存储在一个列表中,然后将它们绑定到一个csv。这些文件中有些是csv文件,有些是xlsx文件。然而,我得到了以下信息: Error: Can't establish that the input is either xls or xlsx. 因此,我想确定哪些是错误的,然后手动附加它 我的职能如下: make_df<-function(filename){ library(readxl) library(foreign) if (
Error: Can't establish that the input is either xls or xlsx.
因此,我想确定哪些是错误的,然后手动附加它
我的职能如下:
make_df<-function(filename){
library(readxl)
library(foreign)
if (str_sub(filename,-3,-1) == "csv"){
df<-read.csv(filename,fileEncoding="latin1")
}
else{
df<-read_excel(filename)
}
return(df)
}
filenames_vector<-list.files(# directory)
datalist = list()
for (i in 1:23){
datalist[[i]] <- make_df(filenames_vector[i])
}
mega_data = do.call(rbind,datalist)
make_df这可以通过tryCatch块完成。没有示例数据,重新创建有点困难。我不知道你的第二个问题是什么意思
尝试下面的代码捕获错误,如果出现错误,则打印文件名,否则返回df对象
make_df<-function(filename){
library(readxl)
library(foreign)
df = tryCatch(
{ # try block
if (str_sub(filename,-3,-1) == "csv"){
df<-read.csv(filename,fileEncoding="latin1")
}
else{
df<-read_excel(filename)
}
},
error=function(cond){return(filename)} # grab the filename if there was an error
)
if (class(df) == 'character') {
print(df)
} else{return(df)}
}
make_df这可以通过tryCatch块完成。没有示例数据,重新创建有点困难。我不知道你的第二个问题是什么意思
尝试下面的代码捕获错误,如果出现错误,则打印文件名,否则返回df对象
make_df<-function(filename){
library(readxl)
library(foreign)
df = tryCatch(
{ # try block
if (str_sub(filename,-3,-1) == "csv"){
df<-read.csv(filename,fileEncoding="latin1")
}
else{
df<-read_excel(filename)
}
},
error=function(cond){return(filename)} # grab the filename if there was an error
)
if (class(df) == 'character') {
print(df)
} else{return(df)}
}
谢谢你!我试试这个。第二个问题只是问是否有其他方法来解决错误消息,因为我不确定是什么导致了问题。谢谢!我试试这个。第二个问题只是询问是否有其他方法来解决错误消息,因为我不确定是什么导致了问题。