R中的ggmap:如何从地理编码中提取单个位置特征?

问题描述 投票:0回答:1

我正在尝试清理用户输入的地址,所以我想使用GGMAP来提取经度/纬度和使用的地址将是一种清理所有内容的方法。但是,它吐出的地址有时在地址中有通俗名称,因此很难解析各个位置方面。

这是我正在使用的代码

for(i in 1:nrow(Raw_Address))
   {
     result <- try(geocode(Raw_Address$Address_Total[i], output = "more", source = "google"))
     Raw_Address$lon[i] <- as.numeric(result[1])
     Raw_Address$lat[i] <- as.numeric(result[2])
     Raw_Address$geoAddress[i] <- as.character(result[3])

   }

我尝试将“latlona”更改为“更多”并查看结果数字,但只返回不同的经度/纬度。我没有在文档中看到显示结果向量的任何地方。

基本上,我想要街道名称,城市,州,邮编,经度和纬度。

编辑:这是一个数据示例

用户输入:1651 SE TIFFANY AVE。 PORT ST。 LUCIE FL

GGMAP输出:马丁卫生系统 - 蒂芙尼大道,1651 se tiffany ave,port st。 lucie,fl 34952,usa

由于口语名称,这很难解析。我可以使用stringr包来尝试解析,但它可能不会包含所有内容。但它返回一个明确的地址,而一些用户拼写“蒂芙尼”错误或拼出“圣”而不是“圣”

r ggmap street-address
1个回答
0
投票

for不是使用purrr::map_dfr循环,而是迭代一个向量并将结果数据帧转换为单个数据帧,这在这里很方便。例如,

library(tidyverse)

libraries <- tribble(
    ~library,                      ~address,
    "Library of Congress",         "101 Independence Ave SE, Washington, DC 20540",
    "British Library",             "96 Euston Rd, London NW1 2DB, UK",
    "New York Public Library",     "476 5th Ave, New York, NY 10018", 
    "Library and Archives Canada", "395 Wellington St, Ottawa, ON K1A 0N4, Canada"
)

library_locations <- map_dfr(libraries$address, ggmap::geocode, 
                             output = "more", source = "dsk")

这会输出很多信息,有些会告诉你geocode正在调用的信息,例如

#> Information from URL : http://www.datasciencetoolkit.org/maps/api/geocode/json?address=101%20Independence%20Ave%20SE,%20Washington,%20DC%2020540&sensor=false

还有一些警告说正在强迫因素:

#> Warning in bind_rows_(x, .id): Unequal factor levels: coercing to character
#> Warning in bind_rows_(x, .id): binding character and factor vector,
#> coercing into character vector

它们应该是什么,所以你可以忽略它们。 (如果你真的想要你可以写更多的代码让它们消失,但你最终会得到同样的东西。)

合并生成的数据框,您将获得链接到原始数据集的所有位置数据:

full_join(libraries, library_locations)
#> Joining, by = "address"
#> # A tibble: 4 x 15
#>   library address      lon   lat type  loctype north south    east     west
#>   <chr>   <chr>      <dbl> <dbl> <chr> <chr>   <dbl> <dbl>   <dbl>    <dbl>
#> 1 Librar… 101 In…  -77.0    38.9 stre… rooftop  38.9  38.9 -77.0    -77.0  
#> 2 Britis… 96 Eus…   -0.125  51.5 stre… rooftop  51.5  51.5  -0.124   -0.126
#> 3 New Yo… 476 5t…  -74.0    40.8 stre… rooftop  40.8  40.8 -74.0    -74.0  
#> 4 Librar… 395 We… -114.     60.1 coun… approx…  83.1  41.7 -52.3   -141.   
#> # … with 5 more variables: street_number <chr>, route <chr>,
#> #   locality <chr>, administrative_area_level_1 <chr>, country <chr>

您可能会注意到,无论出于何种原因,Data Science Toolkit完全没有对加拿大图书馆和档案馆进行地理编码 - 它被标记为国家而不是地址。 Geocoders有时会出错。从这里开始,将你不需要的东西分组。

如果你想要更多的信息,你可以使用geocodeoutput = "all"方法,但是返回一个你需要解析的列表,这需要更多的工作。

© www.soinside.com 2019 - 2024. All rights reserved.