[英]Find top-level element that contains a sub-element in a nested list
I would like to get a list of top level elements that contain a particular sub-element. 我想获取包含特定子元素的顶级元素的列表。 Suppose I have a nested list:
假设我有一个嵌套列表:
v <- list(A=list('a', 'b', 'c'), B=list('c','d','e'), C=list('d'))
I am trying to get the list of all top-level elements that have a particular sub element: 我正在尝试获取具有特定子元素的所有顶级元素的列表:
NOTE: prefer a base-R solution but would be interesting to see others 注意:更喜欢使用base-R解决方案,但是看到其他人会很有趣
You can use Filter
: 您可以使用
Filter
:
names(Filter(function(x) "c" %in% x,v))
# [1] "A" "B"
names(Filter(function(x) "d" %in% x,v))
# [1] "B" "C"
Or with library purrr : 或使用库purrr :
names(purrr::keep(v, ~"c" %in% .))
# [1] "A" "B"
names(purrr::modify_if(v, ~!"c" %in% ., ~NULL))
# [1] "A" "B"
sapply
替代Filter
names(v)[sapply(v, function(x) 'c' %in% x)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.