HelpMe
HelpMe

Reputation: 97

How to Loop Through Excel Rows in R to Use Rows in Code?

I have a CSV file with 20,000 latitude/longitude coordinates. E.g. a sample:

lat    lon
13.2   100.3
12.3   90.2
24.2   78.8

library(googleway)

google_streetview(
  location = c(13.2, 100.3), # lat/lon coordinates
  size = c(600, 400) # image size

Basically, I want the code above to use the lat/lon coordinates from the first row in the CSV file (which returns a Google Street View image of those coordinates), then loop back through the code and replace the lat/lon coordinates with the second line of the CSV file, and so on.

Does anybody know how to do this?

Upvotes: 0

Views: 261

Answers (2)

MonJeanJean
MonJeanJean

Reputation: 2906

You can use the purrr package. Saying your csv is called data:

MyFunction <- function(lat, long){
 google_streetview(location = c(lat,long), size = c(600, 400))
}

purrr::map2(data$lat, data$long, MyFunction)

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 389265

You can use any of the looping functions to iterate over lat and lon values.

For example, using Map -

result <- Map(function(x, y) 
    google_streetview(location = c(x, y), size = c(600, 400)), df$lat, df$lon)

Upvotes: 1

Related Questions