I want to create a data folder relative to my current directory, i.e. I want to move up one folder, then move down another folder (and sub folder) and create a folder.
dir.create
doesn't work because it either only creates the last part of the specified folder or (when setting recursive = TRUE
) it will start creating the folder in the root of your working directory.
I'm struggling with this (supposedly) easy task. Any help?
Here's the code I was using and the error I'm getting:
dir.create("../04 Data/Data downloads/new folder")
Warning message:
In dir.create(download_folder) :
cannot create dir '..\04 Data\Data downloads\new folder', reason 'No such file or directory'
So let's assume this is my current working directory:
"C:/Users/USERNAME/Project/Subfolder/07 R"
and now I want to create the following folder:
"C:/Users/USERNAME/Project/Subfolder/04 Data/Data downloads/new folder"
How can I do that?
recursive = TRUE
is meant to deal with situations where at least one of the parent directories may not exist.
Without it, effectively what is happening is this:
p <- "../04 Data/Data downloads/new folder"
dirname(p)
# [1] "../04 Data/Data downloads"
if (!dir.exists(dirname(0))) stop("nope")
Whereas with recursive = TRUE
, it effectively does this:
p <- "../04 Data/Data downloads/new folder"
paths <- character(0)
while (nzchar(p) && p != ".") { paths <- c(p, paths); p <- dirname(p); }
paths
# [1] ".."
# [2] "../04 Data"
# [3] "../04 Data/Data downloads"
# [4] "../04 Data/Data downloads/new folder"
for (path in paths) if (!dir.exists(path)) dir.create(path)
which should always succeed (unless one of the parent directories is actually a file, or if you don't have permissions).