【问题标题】:find names that match either of two patters [duplicate]查找与两种模式中的任何一种匹配的名称[重复]
【发布时间】:2021-02-13 13:55:16
【问题描述】:

在下面的示例中是否可以在包含idgroup 或两者的向量中找到名称?

我使用grepl()没有成功。

a = c("c-id" = 2, "g_idgroups" = 3, "z+i" = 4)


grepl(c("id", "group"), names(a)) # return name of elements that contain either `id` OR `group` OR both

【问题讨论】:

    标签: r regex string character tidyverse


    【解决方案1】:

    你可以使用:

    pattern <- c("id", "group")
    grep(paste0(pattern, collapse = '|'), names(a), value = TRUE)
    #[1] "c-id"      "g_igroups"
    

    使用grepl 可以获得逻辑值

    grepl(paste0(pattern, collapse = '|'), names(a))
    #[1]  TRUE  TRUE FALSE
    

    stringr 解决方案:

    stringr::str_subset(names(a), paste0(pattern, collapse = '|'))
    #[1] "c-id"      "g_igroups"
    

    【讨论】:

    • 我可以添加另一个模式,比如"id|group|grp"吗?我们也可以使模式不区分大小写吗? "id|group|grp" = "iD|Group|Grp" = "ID|GRoup|GRp"。 . .?
    • 是的,您可以使用| 添加任意数量的模式。要使其不区分大小写,您可以设置 ignore.case = TRUE
    【解决方案2】:

    使用 str_detect:

    > names(a)[str_detect(names(a), 'id|groups')]
    [1] "c-id"       "g_idgroups"
    > names(a)
    [1] "c-id"       "g_idgroups" "z+i"       
    > 
    

    【讨论】:

      猜你喜欢
      • 2018-07-17
      • 2015-03-22
      • 1970-01-01
      • 2020-12-01
      • 2021-12-06
      • 2018-10-06
      • 2013-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多