【问题标题】:Index of unmatched string in a list of character vectors字符向量列表中不匹配字符串的索引
【发布时间】:2019-02-05 04:34:32
【问题描述】:

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

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

我想要一个函数来返回每个向量中不匹配模式的索引。在我的示例中,返回除“hello”之外的所有内容的索引。如果我使用以下内容:

lapply(x.lst, function(x) x[-grep("hello",x)])

我明白了:

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

[[2]]
character(0)

[[3]]
character(0) 

想要的输出是:

[[1]]
[1] 1    2

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

[[3]]
[1] 1    2 

感谢您的帮助!

【问题讨论】:

    标签: r


    【解决方案1】:

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

    lapply(x.lst, function(x) grep("hello",x, invert = TRUE))
    
    #[[1]]
    #[1] 1 2
    
    #[[2]]
    #integer(0)
    
    #[[3]]
    #[1] 1 2
    

    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
    

    【讨论】:

    • 正是我需要的...谢谢 Ronak!
    【解决方案2】:

    Map 的一个选项来自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
    

    【讨论】:

    • 感谢阿克伦!两种解决方案都有效,但看起来 tidyverse 下载了很多东西,所以我喜欢 unname 和 MAP 函数的组合。
    • @seakyourpeak 我个人不会下载所有软件包。我只会使用相关的包,即stringr(str_detect)和purrr(地图)和dplyr
    • 你的意思是如果我只下载 purr 我会很好,因为我已经有了 stringr 和 dplyr
    • 是的,加载library(purrr); library(dplyr);library(stringr)而不是tidyverse中的所有pckages
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 2013-01-19
    • 2013-11-22
    • 2019-07-21
    • 2023-03-28
    • 2012-09-05
    • 1970-01-01
    相关资源
    最近更新 更多