r - 根据条件跳过 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 中的特定值?
解决方案
也许你可以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
推荐阅读
- discord - on_member_update 昵称更改未按预期进行
- opengl - 使用 GL_SAMPLE_ALPHA_TO_COVERAGE 并写入 Alpha 通道
- text-to-speech - PowerShell 中的 Mozilla TTS:“用户警告:具有 CUDA 功能 sm_86 的 NVIDIA GeForce RTX 3060 Ti 与当前的 PyTorch 安装不兼容
- javascript - 显示一个
- python - Keras:输入张量的等级必须为 3、4 或 5,但为 2
- logic - 转换系统和计算树逻辑 - 无法理解这一点
- javascript - (Jquery Validate) onkeyup: false 适用于一个字段,直到我第二次选择它
- c# - 如何使用 OpenXmlAttribute 更改字体大小?
- algorithm - 子串部分数量受限的最长公共子序列
- javascript - 如何使用纯javascript从spritesheet中提取精灵