vendredi 26 juin 2015

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

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
}

Aucun commentaire:

Enregistrer un commentaire