user971102 user971102 - 1 year ago 54
R Question

Extract elements of a list with more than two characters and matching a pattern

I am trying to find the index of a list for which one element matches a specific pattern and has n characters>1, for example:

i = "a"
ll = list(c("a"), c("b", "abc"), c("cc", "b"), c("c", "b"), c("ac", "c"), c("a", "bc"))

I would like to extract ll[[2]] and ll[[5]]. This kind of gets me to the right path, but not quite because I only want the elements that contain the pattern and have nchar>1...

sapply(ll, function(x) sapply(x, function(x) nchar(x)>1 & grep(i, x)))

Thank you!!

Answer Source

We can use Filter. The idea would be to find those elements that have a, subset those, check whether those elements have nchar greater than 1, wrap it with any (if there are more elements in each list element) and Filter it.

Filter(function(x) any(nchar(x[grep(i, x)])>1), ll)
#[1] "b"   "abc"

#[1] "ac" "c" 


Filter(function(x) any(nchar(grep(i, x, value = TRUE))>1), ll)