'Create several folders in a directory with a loop to write the names R
I am trying to create several subfolder in a parent folder. I created this code but it does not create my subfolders. I would like to create subfolders in the folder "xxxx".
setwd<- "path/xxxx"
subfolder_names<- (a, b, c, d)
for (j in1: length(subfolder_names)){
folder<-dir.create("path/xxxx/", paste(j))}
Thanks in advance for your suggestion.
Solution 1:[1]
Some notes:
- Use c() to combine elements into a list and add quotations (") around the strings to make sure R sees them as data and not variables.
- Make sure that "in" and "1:" in the for loop statement are separated by a space and "1:" and "length()" are adjacent to one another.
- In the for loop, paste0 can be used to concatenate two strings. Here we concatenate both the directory and the subfolder name from the subfolder_names list we created.
subfolder_names <- c("a","b","c","d")
for (j in 1:length(subfolder_names)){
folder<-dir.create(paste0("path/xxxx/",subfolder_names[j]))
}
Solution 2:[2]
Based on the comment above, I have this and it works.
subfolder_names <- c("a","b","c","d")
for (j in seq_along(subfolder_names)){
folder<-dir.create(paste0("C:/Users/OGUNDEPO EZEKIEL .A/Desktop/",subfolder_names[j]))}
Solution 3:[3]
This:
base_path <- "path/xxxx"
subfolder_names <- ("a", "b", "c", "d")
for (name in subfolder_names) {
path <- paste0(base_path, "/", name)
dir.create(path)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | gbganalyst |
Solution 3 | VeilOfIgnorance |