我有40栋建筑的数据。每栋建筑都包含二氧化碳,温度,热量等文件夹。然后在每个文件夹里面有不同地区的数据。例如,对于二氧化碳,我有走廊,卧室,客厅等的数据(时间序列集合)。我需要所有这些数据文件的热图。到目前为止,我能做的是,我写了一个代码进入每个目录,然后每个文件夹,然后访问文件,并在Rstudi内绘制热图。代码是:
setwd("C:/Users/...")
folders <- list.dirs(full.names = TRUE)
result <- sapply(folders[-1], function(x){
res<-lapply(files, function (x) {
[some heatmap function]
P1<- ggplot(df, aes(Time, Date, fill =reading)) + geom_tile(colour = "grey") + scale_fill_gradientn(colours=c("darkblue", "red", "yellow"), values=rescale(c(0, 1000, 2000)), guide="colorbar")+scale_x_discrete(breaks = lab1)
plot(P1)
})})
我真正想要的是,将每个文件的热图结果存储在同一文件夹中,文件夹名称+文件名称(如CO2.hallway.jpeg等)。我在过去2天尝试各种代码,但没有一个适合我。任何人都可以帮我这个。我非常感谢你。
答案 0 :(得分:2)
您要做的是更改工作目录或lapply
循环内文件的路径。
像这样的东西
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 = "/"))
})
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)
})
这有帮助吗?
答案 1 :(得分:0)
浏览名称,然后使用dir.create()
函数创建所需的文件夹,然后访问它们。超级简单:http://rfunction.com/archives/2432