【问题标题】:R search a character vector using a pattern vector [duplicate]R使用模式向量搜索字符向量[重复]
【发布时间】:2020-10-30 05:57:35
【问题描述】:

我一直在尝试使用 grep 来识别字符向量中的模式,目的是从字符向量中“找出”文件的名称。例如,对于一个小而简化的案例,假设:

vec <- c("Fast.file1", "Fast.file2", "Med.file3", "Medium.file4", "Slow.file5")

我可以通过简单的写来搜索带有“Fast”模式的文件:

> Fast_files <- vec[grep("Fast", vec)]
> Fast_files
[1] "Fast.file1" "Fast.file2"

但是假设我有一个模式向量,其长度可以根据用户通过文件读取的输入而变化。我想将模式向量提供给搜索,以便可以针对vec 交叉检查模式的每个元素,并且我想返回所有兼容的命中。例如,

checkAgainst &lt;- c("Fast", "Medium", "Med")

如果我尝试使用 grep 和 checkAgainst 作为模式,我会得到:

> find_files <- grep(checkAgainst, vec)
Warning message:
In grep(checkAgainst, vec) :
  argument 'pattern' has length > 1 and only the first element will be used
> find_files
[1] 1 2
> 

所以,看起来 grep 不能采用向量模式。它需要第一个(即“快速”)。

我希望得到一个结果,其中 find_files 包括“Fast.file1”、“Fast.file2”、“Med.file3”和“Medium.file4”。

我可以编写一个 for 循环来解决这个问题,但我想知道 R 是否提供了更简洁和优雅的解决方案?

感谢您的考虑。

马扎尔。

【问题讨论】:

    标签: r


    【解决方案1】:

    你可以形成一个正则表达式交替,然后 grep :

    vec <- c("Fast.file1", "Fast.file2", "Med.file3", "Medium.file4", "Slow.file5")
    checkAgainst <- c("Fast", "Medium", "Med")
    regex <- paste(checkAgainst, collapse="|")
    Fast_files <- vec[grep(regex, vec)]
    Fast_files
    
    [1] "Fast.file1"   "Fast.file2"   "Med.file3"    "Medium.file4"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-07
      • 2023-02-05
      • 2019-07-20
      • 1970-01-01
      • 1970-01-01
      • 2020-03-29
      • 2010-10-24
      • 1970-01-01
      相关资源
      最近更新 更多