简体   繁体   中英

Subsetting list from another list in R

I learnt how to subset a list based on the values of another list. Am however finding aa challenge when I try to replicate the code in a different context: ( I only need to retain the elements with ":" ie 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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM