Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 657
roblanf Avatar asked Sep 11 '17 03:09

roblanf


People also ask

How do you check if a file is a directory or not?

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.

How do you check if a file exists in a directory in R?

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.

How do I check if a csv file exists in R?

Your answer Check out file. exists() function!! The function file. exists() returns a logical vector indicating whether the files named by its argument exist.

How do I find the path of a file in R?

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( ).


2 Answers

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

file.exists(f) && !dir.exists(f) 
like image 53
Hong Ooi Avatar answered Sep 27 '22 21:09

Hong Ooi


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.

like image 28
roblanf Avatar answered Sep 27 '22 22:09

roblanf