您要做的是更改工作目录或lapply-loop 中文件的路径。
类似的东西
setwd("...")
folders <- list.dirs(full.names = T)
res <- sapply(folders[-1], function(dir){
# INSERT OTHER CODE PARTS HERE
P1 <- ggplot(...) + geom_x()
# Option 1
setwd(dir)
ggsave(P1, filename = paste0("CO2.", dir, ".jpg"))
# Or Option2
ggsave(P1, filename = paste(dir, paste0("CO2.", dir, ".jpg"), sep = "/"))
# I encourage you to use pdf (best quality, can be included in LaTeX and Markdown), otherwise png (better quality)
})
添加:最小工作示例
在所有子方向上保存绘图的 MWE 如下所示:
folders <- list.dirs(full.names = T)
lapply(folders[-1], function(dir){
dat <- data.frame(x = 1:10, y = cumsum(rnorm(10)))
P1 <- ggplot(dat, aes(x = x, y = y)) + geom_line()
ggsave(P1, filename = paste(dir, paste0("plot.png"), sep = "/"))
})
添加 v2:MWE 包括读取数据
lapply(folders[-1], function(dir2){
# read the data
files <- list.files(dir2, pattern = "*.csv", recursive = F)
# finds the last "./" and takes everything afterwards
# aka, it returns the up-most folder
folder <- substr(dir2,
start = regexpr("\\./[^\\./]*$", dir2) + 2,
stop = nchar(dir2))
lapply(files, function(file, folder){
# find the filename, aka. exclude .csv
f.name <- substr(file, start = 1,
stop = regexpr(".csv", file) - 1)
# load each file to the loadeddat-data.frame
loadeddat <- read.table(paste(folder, file, sep = "/"))
# plot the data as you wish
P1 <- ggplot(loadeddat, aes(x = x, y = y)) + geom_line()
# create the name for the plot
nam <- paste(folder, # i.e., folder1
paste0(folder, "-", f.name, ".png"), # i.e., folder1-file1.png
sep = "/") # whole name/path looks like this:
# "folder1/folder1-file1.png"
# save it
ggsave(P1, filename = nam)
}, folder = folder)
})
这有帮助吗?