Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Indexing by a value of a categorical variable in a loop in R

I am trying to get coordinates of various cities with R and the osmdata package.
My code looks like this

cities<-c("Name1","Name2")

for (city in cities){
      city <-getbb(
      city,
      format_out = "matrix",
      base_url = "https://nominatim.openstreetmap.org",
      featuretype = "settlement",
      limit = 10,
    )

}

I would like the coordinates to be attributed to the actual name of the city in the loop e.g. for the first iteracy of the loop

Name1<- getbb("Name1")

and so on, but I cannot find a way to index the output of the getbb() function inside the loop with the name of the variable inside the getbb() function.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I do not want to use a number to index the coordinates as I have many cities.

How can I do it ?

>Solution :

When you write a loop, you need to think about how to store the output of each iteration. I suspect that the output of getbb is quite complicated (maybe a two column matrix? "bb" for "bounding box"?), so I would use a "list" for storage.

cities <- c("Name1", "Name2")

## initialize storage
output <- vector("list", length(cities))
## add names to list entries
names(output) <- cities

## a loop with numeric index
for (i in 1:length(cities)) {
      output[[i]] <- getbb(
      cities[i],
      format_out = "matrix",
      base_url = "https://nominatim.openstreetmap.org",
      featuretype = "settlement",
      limit = 10,
    )
}

In the end, you can use city name to extract value from the list:

## result for city "Names1"
output[["Names1"]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading