【问题标题】:Skip specific value in lapply based on a condition根据条件跳过 lapply 中的特定值
【发布时间】:2019-12-21 13:29:36
【问题描述】:

for loop 中,可以使用next() 跳到下一个迭代。如example

# 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 中的特定值?

【问题讨论】:

  • 怎么样 - lapply(na.omit(l), myfun)?
  • 我会在使用lapply 之前过滤l。如果想知道异常发生在哪里,可以使用?tryCatch函数。

标签: r lapply


【解决方案1】:

也许你可以试试return nothing 或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

【讨论】:

    【解决方案2】:

    我们可以做一个forloop

     for(i in seq_along(l)) if(is.na(l[[i]]))  print(NULL) else cat(paste('test', l[[i]]), "\n")
    #test 1 
    #test 2 
    #NULL
    #test 4 
    #test 5 
    

    或使用map_if

    library(purrr)
    library(stringr)
    map_if(l, ~!is.na(.), ~ cat(str_c('test ', .x), '\n'), .else = ~cat(NULL))
    #test 1 
    #test 2 
    #test 4 
    #test 5 
    #[[1]]
    #NULL
    
    #[[2]]
    #NULL
    
    #[[3]]
    #NULL
    
    #[[4]]
    #NULL
    
    #[[5]]
    #NULL
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-21
      • 1970-01-01
      • 2015-11-09
      • 1970-01-01
      相关资源
      最近更新 更多