【问题标题】:Find elements in a character array that contains a string在包含字符串的字符数组中查找元素
【发布时间】:2013-11-01 16:31:45
【问题描述】:

我想提取包含某个特定字符串的字符数组的元素。例如:

x <- c('aa', 'ab', 'ac', 'bb', 'bc')

我想要一些函数,给定x'a'(通常这可以是一个字符串),它返回'aa', 'ab', 'ac'。我已经尝试了%in%matchwhich 等的组合,但无法使它们工作。有什么想法吗?

【问题讨论】:

    标签: string r


    【解决方案1】:

    只需使用grep:

    grep('a', x, value=TRUE)
    [1] "aa" "ab" "ac"
    

    【讨论】:

      【解决方案2】:

      在表格或列表中,我们可以使用 dplyr/tidyverse 包中的 dplyr::pull 将列中的值首先转换为向量,然后在列中找到特定的值。例如,在 LEGO 示例中,我们可以执行以下操作来查找以“s”或“S”开头的任何主题:

       inventory_parts_themes <- inventories %>%
         inner_join(inventory_parts, by = c("id" = "inventory_id")) %>%
           arrange(desc(quantity)) %>%
             select(-id, -version) %>%
               inner_join(sets, by = "set_num") %>%
                  inner_join(themes, by = c("theme_id" = "id"), suffix = c("_set", "_theme"))
      
        all_theme_names <- dplyr::pull(inventory_parts_themes, name_theme) 
        all_theme_names[grep("^[sS].*", all_theme_names)]   
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-11-07
        • 2015-07-05
        • 2016-03-03
        • 1970-01-01
        • 2013-10-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多