如何告诉 lapply 忽略错误并处理列表中的下一个内容? [英] How to tell lapply to ignore an error and process the next thing in the list?
问题描述
我在下面有一个示例函数,它以字符串形式读取日期并将其作为日期对象返回.如果它读取一个不能转换为日期的字符串,它会返回一个错误.
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
现在,我想使用 lapply 并将此函数应用于日期列表:
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)
我想我想在那里尝试捕获,但是有没有办法在要求 lapply 继续读取第三个日期的同时捕获foo"字符串的错误?
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?
推荐答案
在可能抛出错误消息的函数周围使用 tryCatch
表达式:
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))
}
tryCatch
函数的好处在于您可以决定在出现错误时该怎么做(在这种情况下,返回 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, return NULL
).
> lapply(dates2, testFunction)
[[1]]
[1] "2010-04-06"
[[2]]
NULL
[[3]]
[1] "2010-04-08"
这篇关于如何告诉 lapply 忽略错误并处理列表中的下一个内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!