Skip to content
Back to formatted view

Raw Message

Message-ID: <40e66e0b0812210754r52d72eefleeb4d43335bc5167@mail.gmail.com>
Date: 2008-12-21T15:54:25Z
From: Douglas Bates
Subject: Globbing Files in R
In-Reply-To: <73f827b50812210735w3956efe5l5cb0dfe35acc0e27@mail.gmail.com>

On Sun, Dec 21, 2008 at 9:35 AM, Gundala Viswanath <gundalav at gmail.com> wrote:
> Dear all,
>
> For example I want to process set of files.
>
> Typically  Perl's idiom would be:
>
> __BEGIN__
> @files = glob("/mydir/*.txt");
>
> foreach my $file (@files) {
>  # process the file
> }
> __END__
>
> What's the R's way to do that?

The tools to do this are the functions list.files, grep (or variants
on grep) and perhaps glob2rx.  See the help files for each.

One approach is

> files <- list.files("~/Desktop")
> txtfiles <- files[grep(glob2rx("*.txt"), files)]
> txtfiles
[1] "notes312.txt" "stat324.txt"

Note that grep returns a vector of indices into the character vector,
not the character vectors themselves.