Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in R Programming by (7.3k points)

I often find myself writing R scripts that generate a lot of output. I find it cleaner to put this output into its 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))

}

1 Answer

0 votes
by

To check the existence of a directory, you can use the following code:

This code will return TRUE if a directory exists and FALSE otherwise.

dir.exists(file.path(mainDir, subDir))

 

This code will create a directory and if it exists already, it will return FALSE.

dir.create(file.path(mainDir, subDir))

setwd(file.path(mainDir, subDir))

 

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.1k users

Browse Categories

...