Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use apply functions dir.exist and dir.create

Tags:

r

I am trying to use a vector of characters to create a series of directories in my working directory. Nothing recursive, simply iterative. Nothing fancy. as an example, I can do this pretty easily with:

lapply(state.name, dir.create)

which creates 50 directories of all US states in my working directory. I can easily delete them if I want using:

unlink(state.name)

However, what I would really like to do is test to see if any of the directories exist already, and then create the ones that are not already there. I have found similar questions here: Check existence of directory and create if doesn't exist but everything I have found on Stack Exchange and through other Google searches either take a deep dive into the apply family of functions, or explain how to create a single directory in R. The recursive checking and creating I would like to do does not seem to exist. I have come up with the following, and it works, sort of, but it is really only checking the first entry in the vector.

if(!file.exists(state.name)) {lapply(state.name, dir.create)}

If I try to use the lapply function with file.exists, it throws an error.

Any help is greatly appreciated. Thank you.

like image 874
Scott Davidson Avatar asked Dec 05 '25 19:12

Scott Davidson


1 Answers

lapply(state.name, function(x) if(!dir.exists(x)) dir.create(x))
like image 118
Hong Ooi Avatar answered Dec 08 '25 11:12

Hong Ooi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!