Home > Software design >  Indexing by a value of a categorical variable in a loop in R
Indexing by a value of a categorical variable in a loop in R

Time:06-28

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.

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

How can I do it ?

CodePudding user response:

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"]]
  • Related