Subseting a list in R based on another list

Subseting a list in R based on another list

Problem Description:

I would like to subset the elements of list1 based on the ones in list 2. I tried using a for loop but it appears not work. Is there any way to work around it?

list1 <- list("a" = "Variable label a",
              "b" = "Variable label b",
              "c" = "Variable label c",
              "d" = "Variable label d",
              "e" = "Variable label e"
              )

list2 <- list(
  "Variable label a" = "Variable label a",
  "Variable label c" = "Variable label c",
  "Variable label e" = "Variable label e"
  
)


subset <- vector("list")

for (nm in list1){
  if (nm %in% list2){
    subset <- list1
  }
}

Solution – 1

library(purrr)
library(stringr)
list1 |> purrr::keep(names(list1) %in% (names(list2) |> stringr::str_sub(-1,-1)))

Output:

$a
[1] "Variable label a"

$c
[1] "Variable label c"

$e
[1] "Variable label e"
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject