ggmap的revgeocode函数采用经度/纬度格式的输入位置,即c(经度,纬度)。见下文:
revgeocode(c(-122.39150, 37.77374), output = "more")
但是,我有一个data.frame有两列,一列用于纬度,一列用于经度。
df <- data.frame(longitude = c(-122.39150, -73.95945, -77.06136), latitude = c(37.77374, 40.71997, 38.90731))
如何使用dplyr而不是data.table来使revgeocode工作,即从我的data.frame的两列中获取c(经度,纬度)数组?
答案 0 :(得分:2)
使用purrr包的解决方案。
library(purrr)
library(ggmap)
df2 <- map2_dfr(df$longitude, df$latitude, ~revgeocode(c(.x, .y), output = "more"))
df2
# address street_number route
# 1 1145 4th St, San Francisco, CA 94158, USA 1145 4th Street
# 2 93 N 8th St, Brooklyn, NY 11249, USA 93 North 8th Street
# 3 1312 31st St NW, Washington, DC 20007, USA 1312 31st St NW
# neighborhood locality administrative_area_level_2
# 1 South of Market San Francisco San Francisco County
# 2 Williamsburg <NA> Kings County
# 3 Northwest Washington Washington <NA>
# administrative_area_level_1 country postal_code postal_code_suffix political
# 1 California United States 94158 2231 <NA>
# 2 New York United States 11249 2858 Brooklyn
# 3 District of Columbia United States 20007 3345 <NA>
或者您可以将dplyr与rowwise
和do
一起使用,它会返回一个元素。
library(dplyr)
df3 <- df %>%
rowwise() %>%
do(revgeocode(c(.$longitude[1], .$latitude[1]), output = "more")) %>%
ungroup()
df3
# # A tibble: 3 x 11
# address street_number route neighborhood locality administrative_~ administrative_~
# * <chr> <chr> <chr> <chr> <chr> <chr> <chr>
# 1 1145 4th~ 1145 4th S~ South of Ma~ San Fra~ San Francisco C~ California
# 2 93 N 8th~ 93 North~ Williamsburg NA Kings County New York
# 3 1312 31s~ 1312 31st ~ Northwest W~ Washing~ NA District of Col~
# # ... with 4 more variables: country <fct>, postal_code <chr>, postal_code_suffix <chr>,
# # political <fct>