including try() or trycatch() in a for-loop R

时间:2015-06-26 10:22:32

标签: r if-statement for-loop error-handling try-catch

I have 90k folders all of which contain 3 files. I only need the result.xml out of each one of them. I want to put the xmlfiles into a Datatable. It works as long as it dont finds any error causing files. I would like to include to the function that if it finds an xml which is not readable and creats an error, it should proceed the process and skip the file and give me the path of the error causing file.

TF<- "/My/Initial/Desktop/Folder" ######Initial Resultfolder

#List of all Resultfiles
source.files  <- list.files(path=TF,
                        recursive=T,
                        pattern=paste("result.xml")
                        ,full.names=T)
#Create an initial Datatable
data <- read.csv(text="Field1,PostId,ThreadId,UserId,TimeStamp,Upvotes,Downvotes,Flagged,Approved,Deleted,Replies,ReplyTo,Content,Sentiment")
data<- data.table(data.frame(data))
k<-1
for(j in source.files){
temp.data<- data.table(xmlToDataFrame(xmlParse(j)))
data<-rbind(data, temp.data)
#Printing progress
if(k%%1 == 0)
print(k/ length(source.files))
#Move Counter
k <- k+1
}

It works until i want to built in my try function...

TF<- "/My/Initial/Desktop/Folder" ######Initial Resultfolder

#List of all Resultfiles
source.files  <- list.files(path=TF,
                        recursive=T,
                        pattern=paste("result.xml")
                        ,full.names=T)
#Create an initial Datatable
data <- read.csv(text="Field1,PostId,ThreadId,UserId,TimeStamp,Upvotes,Downvotes,Flagged,Approved,Deleted,Replies,ReplyTo,Content,Sentiment")
data<- data.table(data.frame(data))
error.files<- list()
k<-1
for(j in source.files){
if(try(temp.data<- data.table(xmlToDataFrame(xmlParse(j)))!="error")
data<-rbind(data, temp.data)
else{error.files<-rbind(error.files,)j}
#Printing progress
if(k%%1 == 0)
print(k/ length(source.files))
#Move Counter
k <- k+1
}

1 个答案:

答案 0 :(得分:2)

您需要在echo条件中测试try对象的类:

if

(您的代码中至少还有一个拼写错误。)