'How can I reference the vectors directly and not the list in a nested lapply function?

I have a list of vectors:

this_list <- list(a <- c("this one","that one","these two"),b <- c("those some","heres more","two plus this","and one last one"),c <- c("the final one","it ends here"))
search words <- c("one","two")

I want to search the vectors in each element of the list for each/any keywords. I only care if a keyword appears, not which keyword.

lapply(search_words,grepl,lapply(this_list$,'['))
lapply(search_words,grepl,this_list'a')

These will tell me, respectively, if a list element has a keyword and if a vector element has a keyword, by keyword.

I want to have a function that at once search per list element, per vector element if a keyword is in there. sample desired output:

this_list a
search_word "one"
true    true    false
search word "two
false    false    true

this_list b
search_word "one"
false   false   false   true

Even better would be to not breakdown by search_word and just tell me, by list element, if a search word was found in the vectors

this_list  'a'
true    true    true
this_list 'b'
false    false   true  true
...
r


Solution 1:[1]

sapply(this_list, function(L) 
  sapply(search_words, grepl, x = L, simplify = FALSE),
  simplify = FALSE)
# $a
# $a$one
# [1]  TRUE  TRUE FALSE
# $a$two
# [1] FALSE FALSE  TRUE
# $b
# $b$one
# [1] FALSE FALSE FALSE  TRUE
# $b$two
# [1] FALSE FALSE  TRUE FALSE
# $c
# $c$one
# [1]  TRUE FALSE
# $c$two
# [1] FALSE FALSE

or

sapply(this_list, function(L)
  rowSums(sapply(search_words, grepl, x = L, simplify = TRUE)) > 0, 
  simplify = FALSE)
# $a
# [1] TRUE TRUE TRUE
# $b
# [1] FALSE FALSE  TRUE  TRUE
# $c
# [1]  TRUE FALSE

FYI, never use <- inside of a function call like list.

this_list <- list(a <- ..., b <- ...)

This doesn't name the entries in this_list, it produces objects in the current environment named a and b, and puts the contents of those objects into the list without names.

Instead, always use = inside of function calls (unless your intent is to create an object and use the object's contents only, disregarding the name ... this is valid use, but much less common.)

this_list <- list(a = ..., b = ...)

Data

this_list <- list(a = c("this one","that one","these two"),b = c("those some","heres more","two plus this","and one last one"),c = c("the final one","it ends here"))
search_words <- c("one","two")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 r2evans