2016-09-27 84 views
0

我读了很多关于使用tryCatch()(来自本网站和其他人),但我似乎无法得到它的工作。我知道这是一个多余的问题,我很抱歉,但我真的可以使用帮助。跳过R中的错误消息

read.rwl()打破了我的循环,因为我试图读取的一些数据是凌乱的。我想跳过list.rwl中的任何网址,这些网址会中断我的循环,同时还会将作为对象的URL保存为会破坏循环的网址。

itrdb <- read.csv ("itrdb.csv") 
itrdb.rwl <- (itrdb [,7]) 

library (dplR) 

for (i in 1:length(itrdb)) { 
list.rwl <- as.character (rwl.crn [1] [i]) 
skip_with_message = simpleError('Did not work out') 
x <- tryCatch(read.rwl (list.rwl), error = function(e) skip_with_message) 
} 
+1

如果您使用的是非基础包中的函数,则应该包含库()调用所需的所有内容。并且您应该为正在使用的对象包含dput。 –

+0

尝试重新阅读其中一些来源。我怀疑他们建议你像上面那样使用'tryCatch'。 – nrussell

+0

感谢您的有用评论。我知道我没有远程使用tryCatch。我尝试了其他变化无济于事,因此我发布了我的问题。 – ZempOh

回答

0

一旦您使用tryCatch捕获错误,您可以使用它做些事情。在下面的例子中,我只是捕获错误(或产生一个随机数),但您可以调整产生NA或适合您的流量的任何内容。有关更多示例,请参阅?tryCatch

x <- as.list(rep(NA, 10)) 

set.seed(357) 
for (i in 1:10) { 
    feelin.lucky <- runif(1) 

    if (feelin.lucky >= 0.5) { 
    x[[i]] <- tryCatch({ 
     simpleError("this is error") 
    }, error = function(e) e) 
    } else{ 
    x[[i]] <- rnorm(1) 
    } 
} 

> x 
[[1]] 
[1] -1.597783 

[[2]] 
[1] 0.3947471 

[[3]] 
<simpleError: this is error> 

[[4]] 
<simpleError: this is error> 

[[5]] 
<simpleError: this is error> 

[[6]] 
<simpleError: this is error> 

[[7]] 
<simpleError: this is error> 

[[8]] 
<simpleError: this is error> 

[[9]] 
[1] -0.7539072 

[[10]] 
[1] -0.4690151