简体   繁体   中英

Use apply functions dir.exist and dir.create

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))
lapply(state.name[!state.name %in% dir()], dir.create)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM