代码之家  ›  专栏  ›  技术社区  ›  rnorouzian

找到两个模式中任何一个匹配的名字

  •  0
  • rnorouzian  · 技术社区  · 5 年前

    可以在向量中找到包含 id 或者 group 或者两者都在下面的例子中?

    我用过 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
    
    2 回复  |  直到 5 年前
        1
  •  2
  •   Ronak Shah    5 年前

    您可以使用:

    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
    

    A stringr 解决方案:

    stringr::str_subset(names(a), paste0(pattern, collapse = '|'))
    #[1] "c-id"      "g_igroups"
    
        2
  •  0
  •   Karthik S    5 年前

    使用str_detect:

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