我有许多文件夹,其中包含模拟不同阶段的网络jpg。我想进入每个文件夹,列出所有jpg文件,并使用image magick将它们组合成GIF,然后再次转到父级导演。为此,我编写了一个函数:
GIFAnimator <- function(dir){
tic()
print(getwd())
# going to directory with files
setwd(dir)
print("listing files")
# list all image files in the subdir
Plots <- list.files(full.names=TRUE, recursive=TRUE, pattern = ".jpg$")
print("ordering files")
# order them correctly
Plots <- Plots[order(nchar(Plots),Plots)]
print("creating animation frames")
# creating frames for animation (we can use read_plots() directly because it is vectorized)
frames <- image_morph(image_read(Plots), frames = 3)
print("pasting animation frames together")
#creating animation
animation <- image_animate(frames)
print("saving animation")
# saving animation
image_write(animation, paste0("Network",substr(dir,14,nchar(dir)),".gif"))
#going up to the main dir again
setwd("..")
print(getwd())
toc()
}
我的文件夹被命名为“ OutputPlots”,后跟数字(例如OutputPlots23)。因此,我试图将上述功能应用于所有目录:
DirList <- list.files(pattern="OutputPlots*", full.names=TRUE)
DirList <- DirList[order(nchar(DirList),DirList)]
例如,我的网络具有10次迭代的目录列表如下所示:
[1] "./OutputPlots1" "./OutputPlots2" "./OutputPlots3" "./OutputPlots4" "./OutputPlots5" "./OutputPlots6" "./OutputPlots7" "./OutputPlots8" "./OutputPlots9"
[10] "./OutputPlots10"
现在,我想将该功能应用于所有目录,所以我尝试了
sapply(DirList,GIFAnimator)
运行此命令时,遇到了问题。每次函数在第二次迭代时崩溃。更具体地说,该功能完成了将动画帧粘贴在一起的功能,但是在保存第二个文件夹的动画时会自动挂起。有趣的是,当我不使用sapply而是在单独的调用中两次使用该函数时,也会发生这种情况:
GifAnimate(DirList[1])
GifAnimate(DirList[2])
这并不是特定文件夹的问题,因为我尝试了许多不同的组合,并且每个星座中的第二个调用该函数崩溃。