seakyourpeak
seakyourpeak

Reputation: 551

Index of unmatched string in a list of character vectors

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

Answers (2)

akrun
akrun

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

Ronak Shah
Ronak Shah

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

Related Questions