user63230
user63230

Reputation: 4636

extract list element names with NA using purrr::keep

I want to extract the names of elements that are NA in a list.

library(tidyverse)
mlist <- lst(p1 = data.frame(a = c(1, NA)),
            p2 = NA,
            p3 = data.frame(b = c(NA, "test")),
            p4 = NA,
            p5 = c(1, 2, NA))
mlist
# $p1
#    a
# 1  1
# 2 NA

# $p2
# [1] NA

# $p3
#      b
# 1 <NA>
# 2 test

# $p4
# [1] NA

# $p5
# [1]  1  2 NA

The easiest way to do this I found is using base:

names(mlist)[is.na(mlist)]
#[1] "p2" "p4"

But I had originally been trying to do this using purrr::keep and I'm still curious how to do it. I thought this would work:

map(mlist, ~keep(is.na(.))) %>% names()

any simple solution?

thanks

Upvotes: 1

Views: 211

Answers (1)

akrun
akrun

Reputation: 887128

We can use keep directly

library(purrr)
keep(mlist, ~ all(is.na(.x))) %>%
       names
#[1] "p2" "p4"

Or another option with pipe is

mlist %>%
     is.na %>% 
     which %>% 
     names
#[1] "p2" "p4"

Upvotes: 1

Related Questions