[英]Latitude and Longitude coordinates in R
我有一列经纬度组合坐标,格式如下:
coordinates
(-73.2566,44.51513)
我正在尝试获取格式
lat long
73.2566 44.51512
我知道这似乎是一个相对简单的问题,但我似乎找不到解决方案。 我已经尝试过使用gsub()函数,但是不会摆脱括号。
尝试使用此简单功能(需要使用Google API):
google_api <- "https://maps.googleapis.com/maps/api/geocode/json"
geocode <- function(address, verbose=FALSE) {
library(httr)
r <- GET(google_api, query=list(address=address))
stop_for_status(r)
result <- content(r)
first <- result$results[[1]]
df <- as.data.frame(list(lat=first$geometry$location$lat,
lon=first$geometry$location$lng))
return(df)
}
#example
geocode("Suzhou New Matro")
lat lon
1 31.31015 120.6221
使用google API,函数geocode()
以所需的格式返回每个城市的坐标
> library(stringr)
> library(magrittr)
> "(-73.2566, 44.51513)" %>% # take coord as string
+ str_replace_all("[()]", "") %>% # replace parantheses
+ str_split_fixed(", ", n=2) %>% # split up based on comma and space after
+ as.data.frame %>% # turn this to a data frame
+ transmute(lat=V1, long=V2) # rename the variables
lat long
1 -73.2566 44.51513
如果你有这些价值观的载体,它可以很容易地通过这样适应for (i in coords)
其中data.frame
在年底会使用类似的反复加入数据集bind_rows
。
这可能有点太简单了,但是
> coordinates=c(-73.2566,44.51513)
> coordinates
[1] -73.25660 44.51513
> lat=coordinates[1]
> lat
[1] -73.2566
> long=coordinates[2]
> long
[1] 44.51513
https://www.nceas.ucsb.edu/~frazier/RSpatialGuides/ggmap/ggmapCheatsheet.pdf有一个ggmap包。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.