Search code examples
rlapplyggmap

Batch printing ggmaps


Consider a list of 1,000 ggmaps. Let's call this list maps.

How can we print them as .png to the working directory?

The code I'm using for a single ggmap is:

png(filename = "1.png",width=1000, height=1000)
m1<-ggmap(maps[[1]])

print(m1)
dev.off()

I was considering using lapply for something like this:

lapply(maps, function (x) png(filename = "x.png", width=1000, height=1000) x
<-ggmap(maps[[x]]) print(x) dev.off() )

Or a for,

for (x in maps) { png(filename = "x.png", width=1000, height=1000) 
x <-ggmap(maps[[x]]) print(x) dev.off()}

However, I feel this is wrong because of the filename=argument. I am unsure of how to assign element x of the list to it because of the quotes.

I wish not to break the R Session and have to terminate it because it has taken about two hours to and my API queries to get that list of 1,000 ggmaps.


Solution

  • I used for and seq_along as suggested. In the end with the help of the package stringr.

    for (i in seq_along(maps)) {
      filename <-str_c(i,".png")
      png(filename = filename,width=1000, height=1000) 
    m <-ggmap(maps[[i]]) 
    print(m)
    dev.off()