[英]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?然而,当我尝试在不同的上下文中复制代码时,我发现了一个挑战:(我只需要保留带有
":"
的元素,即a
, b
和e
)我将如何处理它?
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.