首页 > 解决方案 > 根据条件跳过 lapply 中的特定值

问题描述

在 afor loop中,可以使用 跳到下一个迭代next()。如本例所示

# skip 3rd iteration and go to next iteration
for(n in 1:5) {
  if(n==3) next 
  cat(n)
}

在将我的函数应用于对象列表时,我想做类似的事情。有点像这样:

l <- c(1:2, NA, 4:5)

myfun <- function(i){
                    if(is.na(i)) next
                    message(paste('test',i))
                    }

lapply(l, myfun)

有没有办法根据条件跳过 lapply 中的特定值?

标签: rlapply

解决方案


也许你可以return什么都不尝试,或者NULL

lapply(l, function(i)  if(is.na(i)) return(NULL) else message(paste('test',i)))

#test 1
#test 2
#test 4
#test 5
#[[1]]
#NULL

#[[2]]
#NULL

#[[3]]
#NULL

#[[4]]
#NULL

#[[5]]
#NULL

推荐阅读