我一直在尝试用grep来识别字符向量中的模式,目的是从字符向量中“提取”文件的名称。例如,对于一个小而简单的情况,让我们假设:
vec <- c("Fast.file1", "Fast.file2", "Med.file3", "Medium.file4", "Slow.file5")
我可以用模式“快速”搜索文件,只需写:
> Fast_files <- vec[grep("Fast", vec)]
> Fast_files
[1] "Fast.file1" "Fast.file2"但是假设我有一个模式向量,它的长度可以根据用户通过文件读取的输入而变化。我想将模式向量提供给搜索,这样模式的每个元素都可以与vec交叉检查,并且我想返回所有兼容的点击。例如,
checkAgainst <- c("Fast", "Medium", "Med")
如果我尝试在checkAgainst中使用grep作为一种模式,我会得到:
> 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是否提供了一个更简洁和优雅的解决方案?
谢谢你的考虑。
马齐亚。
发布于 2020-10-30 06:09:50
您可以形成regex交替,然后对此进行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"https://stackoverflow.com/questions/64603374
复制相似问题