R test if a file exists, and is not a directory -
i have r script takes file input, , want general way know whether input file exists, , not directory.
in python way: how check whether file exists using python?, struggling find similar in r.
what i'd below, assuming file.txt
exists:
input.good = "~/directory/file.txt" input.bad = "~/directory/" is.file(input.good) # should return true is.file(input.bad) #should return false
r has called file.exists(), doesn't distinguish files directories.
the solution use file_test()
this gives shell-style file tests, , can distinguish files 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 manual:
usage
file_test(op, x, y) arguments
op character string specifying test performed. unary tests (only x used) "-f" (existence , not being directory), "-d" (existence , directory) , "-x" (executable file or searchable directory). binary tests "-nt" (strictly newer than, using modification dates) , "-ot" (strictly older than): in both cases test false unless both files exist.
x, y character vectors giving file paths.
Comments
Post a Comment