HelpMePlease
HelpMePlease

Reputation: 73

How to amend R code slightly so that multiple images are saved instead of one?

I have a CSV file (data) which contains 10,000+ latitude/longitude coordinates. A sample:

Lat   Lon
13.4  100.3
13.1  100.2

The code below uses an API key to access Google Street View images corresponding to these lat/lon coordinates and attempts to save them to my hard drive with the filename as 'Lat-Lon.jpeg', e.g. the first image should be named '13.4-100.3.jpeg'

MyFunction <- function(Lat, Lon){
  google_streetview(
  location = c(Lat, Lng), # lat/lng coordinates
  size = c(600, 400), # w x h
  key = key
)
}

jpeg(paste0(data$Lat, "-", data$Lon, ".jpeg"))
purrr::map2(data$Lat, data$Lon, MyFunction)
dev.off()

However, running this code only saves the last image to my hard drive, named in the 'Lat-Lon.jpeg' format. How do I amend the code so that all images are saved with their corresponding coordinates too?

Upvotes: 0

Views: 27

Answers (2)

akrun
akrun

Reputation: 887163

We can use a lambda function inside the map2

library(purrr)
map2(data$Lat, data$Lon, ~ {
        jpeg(paste0(.x, "-", .y, ".jpeg"))
        MyFunction(.x, .y)
        dev.off()
       })

Or another option is pmap

pmap(data, ~ {
            jpeg(paste0(..1, "-", ..2, ".jpeg"))
            MyFunction(..1, ..2)
            dev.off()
      })

Or use base R

Map(function(x, y) {
         jpeg(paste0(x, "-", y, ".jpeg"))
         MyFunction(x, y)
        dev.off()},
                 data$Lat, data$Lon)

Upvotes: 1

Nullius in Verba
Nullius in Verba

Reputation: 1

Try putting the jpeg and dev.off inside the function.

Upvotes: 0

Related Questions