Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check existence of directory and create if doesn't exist

Tags:

r

I often find myself writing R scripts that generate a lot of output. I find it cleaner to put this output into it's own directory(s). What I've written below will check for the existence of a directory and move into it, or create the directory and then move into it. Is there a better way to approach this?

mainDir <- "c:/path/to/main/dir" subDir <- "outputDirectory"  if (file.exists(subDir)){     setwd(file.path(mainDir, subDir)) } else {     dir.create(file.path(mainDir, subDir))     setwd(file.path(mainDir, subDir))  } 
like image 715
Chase Avatar asked Nov 18 '10 15:11

Chase


People also ask

How do you check if a folder exists and if not create it?

You can use os. path. exists('<folder_path>') to check folder exists or not.

How do you check and create directory in shell script if not exists?

You can either use an if statement to check if the directory exists or not. If it does not exits, then create the directory. You can directory use mkdir with -p option to create a directory. It will check if the directory is not available it will.

Does mkdir check if directory exists?

mkdir WILL give you an error if the directory already exists. mkdir -p WILL NOT give you an error if the directory already exists. Also, the directory will remain untouched i.e. the contents are preserved as they were.


1 Answers

Use showWarnings = FALSE:

dir.create(file.path(mainDir, subDir), showWarnings = FALSE) setwd(file.path(mainDir, subDir)) 

dir.create() does not crash if the directory already exists, it just prints out a warning. So if you can live with seeing warnings, there is no problem with just doing this:

dir.create(file.path(mainDir, subDir)) setwd(file.path(mainDir, subDir)) 
like image 55
robbrit Avatar answered Nov 12 '22 12:11

robbrit