简体   繁体   English

使用应用函数dir.exist和dir.create

[英]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. 它在我的工作目录中创建了美国所有州的50个目录。 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. 我在这里找到了类似的问题: 检查目录是否存在并创建如果不存在但是我在Stack Exchange上找到的所有内容以及通过其他Google搜索都要深入了解apply函数系列,或者解释如何创建单个函数R中的目录。我想做的递归检查和创建似乎不存在。 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. 如果我尝试在file.exists中使用lapply函数,则会抛出错误。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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