如何告诉lapply忽略错误并处理列表中的下一件事? [英] How to tell lapply to ignore an error and process the next thing in the list?
问题描述
我有一个下面的例子函数,它以字符串的形式读取日期并将其作为日期对象返回。如果它读取一个不能转换为日期的字符串,则返回错误。
testFunction< - function(date_in) {
return(as.Date(date_in))
}
testFunction(2010-04-06)#这个工程很好
testFunction(foo )#这会返回错误
现在,我想使用lapply并将此函数应用于日期:
dates1 = c(2010-04-06,2010-04-07,2010-04 -08)
lapply(dates1,testFunction)#这个工作很好
但是如果我想要在一个列表中应用这个函数,当两个好的日期中间的一个字符串返回一个错误时,处理这个的最好方法是什么?
dates2 = c(2010-04-06,foo,2010-04-08)
lapply(dates2,testFunction)
我假设我想在那里试试,但是有一种方法来抓住foo字符串的错误,同时请求lapply继续阅读第三个日期?
使用一个 tryCatch
表达式可以抛出错误消息的功能:
testFunction< - function(date_in){
/ pre>
return(tryCatch(as.Date(date_in),error = function(e)NULL))
}
关于
tryCatch
功能的好东西是,您可以决定在错误(在这种情况下,返回NULL
)。> lapply(dates2,testFunction)
[[1]]
[1]2010-04-06
[[2]]
NULL
[[3]]
[1]2010-04-08
I have an example function below that reads in a date as a string and returns it as a date object. If it reads a string that it cannot convert to a date, it returns an error.
testFunction <- function (date_in) { return(as.Date(date_in)) } testFunction("2010-04-06") # this works fine testFunction("foo") # this returns an error
Now, I want to use lapply and apply this function over a list of dates:
dates1 = c("2010-04-06", "2010-04-07", "2010-04-08") lapply(dates1, testFunction) # this works fine
But if I want to apply the function over a list when one string in the middle of two good dates returns an error, what is the best way to deal with this?
dates2 = c("2010-04-06", "foo", "2010-04-08") lapply(dates2, testFunction)
I presume that I want a try catch in there, but is there a way to catch the error for the "foo" string whilst asking lapply to continue and read the third date?
解决方案Use a
tryCatch
expression around the function that can throw the error message:testFunction <- function (date_in) { return(tryCatch(as.Date(date_in), error=function(e) NULL)) }
The nice thing about the
tryCatch
function is that you can decide what to do in the case of an error (in this case, returnNULL
).> lapply(dates2, testFunction) [[1]] [1] "2010-04-06" [[2]] NULL [[3]] [1] "2010-04-08"
这篇关于如何告诉lapply忽略错误并处理列表中的下一件事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!