Reputation: 12087
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
Upvotes: 1
Views: 203
Reputation: 47350
You can use 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 :
names(purrr::keep(v, ~"c" %in% .))
# [1] "A" "B"
names(purrr::modify_if(v, ~!"c" %in% ., ~NULL))
# [1] "A" "B"
Upvotes: 2
Reputation: 11802
sapply
alternative to Filter
names(v)[sapply(v, function(x) 'c' %in% x)]
Upvotes: 2