【问题标题】:including try() or trycatch() in a for-loop R在 for 循环 R 中包括 try() 或 trycatch()
【发布时间】:2015-06-26 10:22:32
【问题描述】:

我有 90k 个文件夹,所有文件夹都包含 3 个文件。我只需要它们中的每一个中的 result.xml。我想将 xmlfiles 放入数据表中。只要它没有发现任何导致文件的错误,它就可以工作。我想在函数中包含如果它发现一个不可读的 xml 并产生错误,它应该继续该过程并跳过文件并给我导致错误的文件的路径。

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
}

在我想内置我的 try 函数之前它一直有效...

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
}

【问题讨论】:

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


    【解决方案1】:

    您需要在if 条件下测试try 对象的类:

    x <- try(stop("error")); class(x) == "try-error"
    #[1] TRUE
    
    y <- try(1); class(y) == "try-error"
    #[1] FALSE
    

    (您的代码中至少还有一个错字。)

    【讨论】:

      猜你喜欢
      • 2013-06-06
      • 1970-01-01
      • 2020-03-23
      • 2015-06-01
      • 2015-08-20
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多