string R - 在包含字符串的字符数组中查找元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19731071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:08:22  来源:igfitidea点击:

R - find elements in a character array that contains a string

stringr

提问by Se?or O

I want to extract the elements of a character array that contains some particular string. For example:

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

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

I want some function such that, given xand 'a'(in general this can be a string), it returns 'aa', 'ab', 'ac'. I have experimented with a combination of %in%, match, which, etc, but have not been able to make them work. Any idea?

我想要一些函数,这样,给定x'a'(通常这可以是一个字符串),它返回'aa', 'ab', 'ac'. 我已经尝试的组合%in%matchwhich等,但一直无法让他们的工作。任何的想法?

回答by Se?or O

Just use grep:

只需使用grep

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

回答by Hanif

In a table or a list, we can use dplyr::pull from dplyr/tidyverse package to convert values in a column to a vector first and then find the particular value in the column. For instance, in the LEGO example, we can do the following to find any theme starting by "s" or "S":

在表格或列表中,我们可以使用 dplyr/tidyverse 包中的 dplyr::pull 将列中的值先转换为向量,然后在列中找到特定的值。例如,在乐高示例中,我们可以执行以下操作来查找以“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)]