gpt4 book ai didi

R 允许 lapply 错误

转载 作者:行者123 更新时间:2023-12-02 17:24:15 30 4
gpt4 key购买 nike

this 有关问题。我想构建一个简单的 lapply 函数,如果发生错误,它将输出 NULL。

我的第一个想法是做类似的事情

lapply_with_error <- function(X,FUN,...){    
lapply(X,tryCatch({FUN},error=function(e) NULL))
}

tmpfun <- function(x){
if (x==9){
stop("There is something strange in the neiborhood")
} else {
paste0("This is number", x)
}
}


tmp <- lapply_with_error(1:10,tmpfun )

但是 tryCatch 并没有捕获它看起来的错误。有什么想法吗?

最佳答案

你需要为lapply提供一个函数:

lapply_with_error <- function(X,FUN,...){    
lapply(X, function(x, ...) tryCatch(FUN(x, ...),
error=function(e) NULL))
}

关于R 允许 lapply 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40089885/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com