I try to create the same folders in multiple subdirectories in R. I thought I could do this with a for loop, but it did not go as planned
My folder structure is like this: Main directory/Weather_day . Weather_day contains the folders D0 and D1. I want to create the folders weather and temperature in both D0 and D1
It tried to do it like this with a for loop
pathway = "./Weather_day"
for (i in pathway){
setwd(i)
dir.create("weather")
dir.create("temperature")
}
However, the outcome of this is that it creates the folders in the main directory folder. Furthermore, I cannot run this code twice or more because it changes the working directory.
Any solutions for this? Thanks in advance
I suggest the Weather_day folder is already created. According to your comment my suggestion is as follows.
Furthermore a function also provides additional use, for example if in future you have an additional folder you can simply add it with the function.
wd = getwd()
pathway = paste0(wd,"/Weather_day/")
dir.create(pathway)
create_dir = function (x) {
for (i in x){
if(!dir.exists(paste0(pathway, i))){dir.create(paste0(pathway, i))}
}}
create_dir(c("weather","temperature"))
I checked the code and with the if statement you prevent overwriting existing folders which I highly suggest. But it depends on the use case.
Edit
Regarding your comment I adjusted my suggestion. I am not sure if it is exactly what you are looking for:
pathway = paste0(getwd(),"/Weather_day/")
d = c("D0","D1")
x = c("weather", "temperature")
create_dir = function (d, x) {
for (i in d){
if(!dir.exists(paste0(pathway, i))){dir.create(paste0(pathway, i))}
for (j in x){
if(!dir.exists(paste0(pathway, i, "/", j))){dir.create(paste0(pathway, i, "/", j))}
}}}
create_dir(d,x)
With the code above you get each of the folders weather and temperature in folder D0 and D1.