OK, I have a little problem which I believe I can solve with
my_query<- c('g1', 'g2', 'g3')
It seems to me that there is no easy way to do this without a loop. For each element in
my_query, we can use either of the below functions to get
f1 <- function (pattern, x) length(grep(pattern, x)) > 0L f2 <- function (pattern, x) any(grepl(pattern, x))
f1(my_query, my_data) #  FALSE f2(my_query, my_data) #  FALSE
Then, we use
*apply loop to apply, say
f2 to all elements of
which(unlist(lapply(my_query, f2, x = my_data))) #  2
Thanks, that seems to work. To be honest, I preferred to your one-line original version. I am not sure why you edited with creating another function to call afterwards with
*apply. Is there any advantage as compared to
which(lengths(lapply(my_query, grep, my_data)) > 0L)?
Well, I am not entirely sure. When I read
One advantage of ‘lengths(x)’ is its use as a more efficient version of ‘sapply(x, length)’ and similar ‘*apply’ calls to ‘length’.
I don't know how much more efficient that
lengths is compared with
sapply. Anyway, if it is still a loop, then my original suggestion
which(lengths(lapply(my_query, grep, my_data)) > 0L) is performing 2 loops. My edit is essentially combining two loops together, hopefully to get some boost (if not too tiny).
You can still arrange my new edit into a single line:
which(unlist(lapply(my_query, function (pattern, x) any(grepl(pattern, x)), x = my_data)))
which(unlist(lapply(my_query, function (pattern) any(grepl(pattern, my_data)))))