Scransom
Scransom

Reputation: 3345

Get list of files in a directory without subdirectory names

The base R function list.files lists all the files in a given path.

The default

aa <- list.files(path = ".")

Returns a vector of the names of everything in ., e.g.:

 [1] "dir1" "file1.R"

I want it just to return "file1.R".


A clunky solution is if I call instead

bb <- list.files(path = ".", include.dirs = FALSE, recursive = TRUE)

I get

[1] "dir1/file2.R" "file1.R"

So I can get what I want by calling

intersect(aa, bb)

[1] "file1.R"

But it seems silly to create two objects and intersect them when I feel like list.files can probably give me this directly, I just can't figure out how.

Do you know?

Upvotes: 0

Views: 1499

Answers (1)

Gray
Gray

Reputation: 1398

Using list.files(path = ".") displays the files in the folder where you are currently working.

You are correct. Using the list.files()function can provide additional information about the files in this folder. But getting that additional information using this function will require knowing something about regex.

Using the list.files() function with the metacharacter $ will return all of those .r files in this folder. If there are other files ending with the letter r, then those files will also be returned.

The following will return those .r files you want, and this should provide an answer your question.

list.files(pattern = "r$")

Upvotes: 1

Related Questions