Home > Mobile >  Subseting a list in R based on another list
Subseting a list in R based on another list

Time:12-06

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
  }
}

CodePudding user response:

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"
  •  Tags:  
  • r
  • Related