R test if a file exists, and is not a directory

The solution is to use file_test()

This gives shell-style file tests, and can distinguish files from folders.

E.g.

input.good = "~/directory/file.txt"
input.bad = "~/directory/"

file_test("-f", input.good) # returns TRUE
file_test("-f", input.bad) #returns FALSE

From the manual:

Usage

file_test(op, x, y) Arguments

op a character string specifying the test to be performed. Unary tests (only x is used) are "-f" (existence and not being a directory), "-d" (existence and directory) and "-x" (executable as a file or searchable as a directory). Binary tests are "-nt" (strictly newer than, using the modification dates) and "-ot" (strictly older than): in both cases the test is false unless both files exist.

x, y character vectors giving file paths.


There is a dir.exists function in all recent versions of R.

file.exists(f) && !dir.exists(f)

Tags:

File

Directory

R