I have an R script that takes a file as input, and I want a general way to know whether the input is a file that exists, and is not a directory.
In Python you would do it this way: How do I check whether a file exists using Python?, but I was struggling to find anything similar in R.
What I'd like is something like below, assuming that the file.txt
actually 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 something called file.exists(), but this doesn't distinguish files from directories.
isDirectory() checks whether a file with the specified abstract path name is a directory or not. This method returns true if the file specified by the abstract path name is a directory and false otherwise.
Method 1: Using File.exists() The function file. exists() returns a logical vector indicating whether the file mentioned in the function existing or not. Note: Make sure that to provide a file path for those, not in the current working directory. Return value: The function file.
Your answer Check out file. exists() function!! The function file. exists() returns a logical vector indicating whether the files named by its argument exist.
If we want to check the current directory of the R script, we can use getwd( ) function. For getwd( ), no need to pass any parameters. If we run this function we will get the current working directory or current path of the R script. To change the current working directory we need to use a function called setwd( ).
There is a dir.exists
function in all recent versions of R.
file.exists(f) && !dir.exists(f)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With