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.
lapply(state.name, function(x) if(!dir.exists(x)) dir.create(x))
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