1

I want to keep all the elements of a list where the children contain a certain named element. For example, in this I only want the elements that contain the child "phone" (elements, 1, 3 and 5).

my_list <- list(list(phone = "123-124-1234",
          school = "Midvale"),
     list(address = "123 Main Street",
          color = "blue"),
     list(phone = "124345654"),
     list(color = "green"),
     list(color = "red",
          phone = "12453466"))

Using the purrr package is ideal for me. Related to this question.

Jeff Parker
  • 1,809
  • 1
  • 18
  • 28

2 Answers2

2
my_list %>%
  keep(., ~"phone" %in% names(.))
Jeff Parker
  • 1,809
  • 1
  • 18
  • 28
1

In base R we can use Filter :

Filter(function(x) 'phone' %in% names(x), my_list)

#[[1]]
#[[1]]$phone
#[1] "123-124-1234"

#[[1]]$school
#[1] "Midvale"


#[[2]]
#[[2]]$phone
#[1] "124345654"


#[[3]]
#[[3]]$color
#[1] "red"

#[[3]]$phone
#[1] "12453466"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213