在r中循环中的分类变量值索引

发布于 2025-02-11 10:26:19 字数 503 浏览 2 评论 0原文

我正在尝试通过R和OSMDATA软件包获得各个城市的坐标。 我的代码看起来像这样,

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

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

}

我希望坐标归因于循环中的循环中的城市的实际名称,例如,循环的第一个迭代

Name1<- getbb("Name1")

等等,但我找不到一种方法来索引getBB()的输出在循环内部具有getBB()函数中变量名称的函数。

我不想使用数字来索引坐标,因为我有很多城市。

我该怎么做?

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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冰雪梦之恋 2025-02-18 10:26:19

编写循环时,您需要考虑如何存储每次迭代的输出。我怀疑getBb的输出非常复杂(也许是两个列矩阵?“ bb”用于“边界框”?),所以我将使用“列表”进行存储。

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,
    )
}

最后,您可以使用城市名称从列表中提取值:

## result for city "Names1"
output[["Names1"]]

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"]]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文