簡體   English   中英

R 中另一個列表的子集列表

[英]Subsetting list from another list in R

我學習了如何根據另一個列表的值對列表進行子集化。 然而,當我嘗試在不同的上下文中復制代碼時,我發現了一個挑戰:(我只需要保留帶有":"的元素,即abe )我將如何處理它?

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

怎么樣

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM