В for 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 на основе условия?

1
rafa.pereira 15 Авг 2019 в 04:58

2 ответа

Лучший ответ

Может быть, вы можете попробовать 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
1
Ronak Shah 15 Авг 2019 в 02:03

Мы можем сделать цикл for

 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
0
akrun 15 Авг 2019 в 03:12