列出 R 中不匹配模式的文件 [英] List files in R that do NOT match a pattern

查看:46
本文介绍了列出 R 中不匹配模式的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

R 有一个函数可以列出目录中的文件,就是list.files().它带有可选参数 pattern= 以仅列出与模式匹配的文件.

R has a function to list files in a directory, which is list.files(). It comes with the optional parameter pattern= to list only files that match the pattern.

目录 data 中的文件:File1.csv File2.csv new_File1.csv new_File2.csv

list.files(path="data", pattern="new_")

结果为 [1] "new_File1.csv" "new_File2.csv".

但是我怎样才能反转搜索,即只列出File1.csvFile2.csv?

But how can I invert the search, i.e. list only File1.csv and File2.csv?

推荐答案

我相信你必须自己做,因为 list.files 不支持 Perl 正则表达式(所以你不能做类似于 pattern=^(?!new_)).

I belive you will have to do it yourself, as list.files does not support Perl regex (so you couldn't do something like pattern=^(?!new_)).

即列出所有文件,然后用 grep 过滤它们:

i.e. list all files then filter them with grep:

grep(list.files(path="data"), pattern='new_', invert=TRUE, value=TRUE)

grep(...) 进行模式匹配;invert=TRUE 反转匹配;value=TRUE 返回匹配的值(即文件名)而不是匹配的索引.

The grep(...) does the pattern matching; invert=TRUE inverts the match; value=TRUE returns the values of the matches (i.e. the filenames) rather than the indices of the matches.

这篇关于列出 R 中不匹配模式的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆