Reputation: 551
I have a list of character vectors and I want to use grep command to find locations of what is not matched. See example below:
x.lst <- list()
x.lst[[1]] <- c("she", "said", "hello")
x.lst[[2]] <- c("hello")
x.lst[[3]] <- c("whats", "up")
I want a function to return index of unmatched pattern in each vector. In my example, return index of everything except "hello". If I use following :
lapply(x.lst, function(x) x[-grep("hello",x)])
I get:
[[1]]
[1] "she" "said"
[[2]]
character(0)
[[3]]
character(0)
the desired output is:
[[1]]
[1] 1 2
[[2]]
[1] character(0)
[[3]]
[1] 1 2
Thanks for your help!
Upvotes: 1
Views: 260
Reputation: 887028
One option with Map
from base R
unname(Map(grep, pattern = "hello", x.lst, invert = TRUE))
Or using tidyverse
library(tidyverse)
map(x.lst, ~ str_detect(.x, "hello") %>%
`!` %>%
which)
#[[1]]
#[1] 1 2
#[[2]]
#integer(0)
#[[3]]
#[1] 1 2
Upvotes: 1
Reputation: 388862
Use invert = TRUE
to return the index of the elements which do not match.
lapply(x.lst, function(x) grep("hello",x, invert = TRUE))
#[[1]]
#[1] 1 2
#[[2]]
#integer(0)
#[[3]]
#[1] 1 2
A tidyverse
alternative
library(tidyverse)
map(x.lst, ~ setdiff(seq_along(.), str_which(., "hello")))
#You can always do same as base here as well
#map(x.lst, ~ grep("hello",., invert = TRUE))
#[[1]]
#[1] 1 2
#[[2]]
#integer(0)
#[[3]]
#[1] 1 2
Upvotes: 2