R 字符向量列表中不匹配字符串的索引

R 字符向量列表中不匹配字符串的索引,r,R,我有一个字符向量列表,我想使用grep命令查找不匹配的位置。见下例: x.lst <- list() x.lst[[1]] <- c("she", "said", "hello") x.lst[[2]] <- c("hello") x.lst[[3]] <- c("whats", "up") 我得到: [[1]] [1] "she" "said" [[2]] character(0) [[3]] character(0) 所需输出为: [[1]] [1] 1

我有一个字符向量列表,我想使用grep命令查找不匹配的位置。见下例:

x.lst <- list()
x.lst[[1]] <- c("she", "said", "hello")
x.lst[[2]] <- c("hello")
x.lst[[3]] <- c("whats", "up")
我得到:

[[1]]
[1] "she"  "said"

[[2]]
character(0)

[[3]]
character(0) 
所需输出为:

[[1]]
[1] 1    2

[[2]]
[1] character(0)

[[3]]
[1] 1    2 

谢谢你的帮助

使用
invert=TRUE
返回不匹配元素的索引

lapply(x.lst, function(x) grep("hello",x, invert = TRUE))

#[[1]]
#[1] 1 2

#[[2]]
#integer(0)

#[[3]]
#[1] 1 2

A
tidyverse
备选方案

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

一个带有
Map
from
base R

unname(Map(grep, pattern = "hello", x.lst, invert = TRUE))

或者使用
tidyverse

library(tidyverse)
map(x.lst, ~ str_detect(.x, "hello") %>% 
               `!` %>% 
                which)
#[[1]]
#[1] 1 2

#[[2]]
#integer(0)

#[[3]]
#[1] 1 2

正是我需要的。。。谢谢Ronak!谢谢阿克伦!这两种解决方案都能工作,但看起来tidyverse下载了很多东西,所以我喜欢unname和MAP功能的组合。@seakyourpeak我个人并不下载所有的软件包。我只会使用相关的软件包,即
stringr
(str_detect)和
purrr
(map)和
dplyr
,你的意思是,如果我只下载purr,我会很好,因为我已经有了stringr和dplyrYes,并加载
库(purrr);图书馆(dplyr);库(stringr)
而不是tidyverse中的所有pckages
library(tidyverse)
map(x.lst, ~ str_detect(.x, "hello") %>% 
               `!` %>% 
                which)
#[[1]]
#[1] 1 2

#[[2]]
#integer(0)

#[[3]]
#[1] 1 2