Home > Mobile >  Subsetting list from another list in R
Subsetting list from another list in R

Time:12-06

I learnt how to subset a list based on the values of another list. Am however finding a a challenge when I try to replicate the code in a different context: ( I only need to retain the elements with ":" i.e. a, b and e) How would I have gone about it?

library(stringr)

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


list2 <- vector("list")


for (i in list1){

  if(str_detect(i, ":")){
    list2[[i]] <- i

  }
}

list1 |> purrr::keep(names(list1) %in% (names(list2) |> stringr::str_sub(-1,-1))) # Thanks to Julian

CodePudding user response:

How about

> Filter(Negate(is.na),lapply(list1,function(x){ifelse(grepl(":",x),x,NA)}))
$a
[1] "Variable label a: Docket"

$b
[1] "Variable label b: Boset"

$d
[1] "Variable label d: Kamba"
  •  Tags:  
  • r
  • Related