Reputation: 4655
I'm currently using for loop to save my graphs to the working directory what ever it is. OTH, I want to add one more feature that creating the directory with the graph name and store corresponding figures to those folder. For instance if the graph name is setosa
create folder named setosa
and store setosa
graph to inside to that new directory.
There is a one relative how-to-save-plots-inside-a-folder here but no solution is clearly given.
Here is my current working code for saving graphs to working directory.
library(ggplot2)
library(dplyr)
plot_list = list() # Initialize an empty list
for (i in unique(iris$Species)) {
p = ggplot(iris[iris$Species == i, ], aes(x=Sepal.Length, y=Sepal.Width)) +
geom_point(size = 3, aes(colour = Species))
plot_list[[i]] = p
}
for (i in unique(iris$Species)) {
file_name = paste( i, ".tiff", sep="")
tiff(file_name)
print(plot_list[[i]])
dev.off()
}
Upvotes: 1
Views: 260
Reputation: 6584
Suppose that you set i
to "setosa"
.
i <- "setosa"
Using file.path()
is IMHO the most idiomatic way to create the file name:
filename <- file.path(".", i, paste0(i, ".tiff"))
This has the advantage of also being platform independent (as opposed to inserting /
explicitly into path).
The only thing that remains is to ensure that the folder exists.
dir.create(i, showWarnings = FALSE)
The showWarnings = FALSE
option suppresses the warning if the folder already exists.
Upvotes: 0
Reputation: 39
such as
fillname<-paste0("./","mey", "/",i,".tiff",sep = "")
"mey" is the subdirectory folder.
Upvotes: 0
Reputation: 8305
Replace file_name = ...
with:
...
file_name = paste0("./", i, "/", i, ".tiff")
...
Upvotes: 4