简体   繁体   中英

Getting lat and lon coordinates for ggmap in R

I have data from the iOS Moves app which is in the form:

timeAtSite   location
800.52        {"lat": 38.87212, "lon": -94.61764}
116.40        {"lat": 38.91571, "lon": -94.64835}
14.48         {"lat": 38.91461, "lon": -94.64795}

I have tried a variety of unsucessful methods to get the location data into separate lat and lon columns (example below):

al1 = get_map(location = c(lon: -94.61764, lat: 38.87212), zoom = 2, maptype = 'roadmap')
al1MAP = ggmap(al1)
al1MAP
al1MAP <- ggmap(al1)+ geom_point(data=c(moves$Location["lat"],moves$Location["lon"]))

TIA

You could try

library(stringr)
df[c('lat', 'lon')] <- do.call(rbind,lapply(str_extract_all(df$location,
                                                  '[-0-9.]+'), as.numeric))

Or

library(tidyr)
df1 <- extract(df, location, c('lat', 'lon'), '([-0-9.]+)[^-0-9.]+([-0-9.]+)', 
                    convert=TRUE)
df1
#  timeAtSite      lat       lon
#1     800.52 38.87212 -94.61764
#2     116.40 38.91571 -94.64835
#3      14.48 38.91461 -94.64795

Once you extracted the location,

center <-  paste(min(df1$lat)+(max(df1$lat)-min(df1$lat))/2,
            min(df1$lon)+(max(df1$lon)-min(df1$lon))/2, sep=" ")

df1$id <- 1:3
library(ggmap)
al1 <- get_map(location = center, zoom = 11, maptype = "roadmap" )

p <- ggmap(al1)


p <- p + geom_text(data=df1,aes(x = lon, y = lat, label=id),
     colour="red",size=4,hjust=0, vjust=0)+
      theme(legend.position = "none") 

p <- p + geom_point(data=df1,aes(x=lon, y=lat),colour="black",size=2)
p

data

df <- structure(list(timeAtSite = c(800.52, 116.4, 14.48), location =
 c("{\"lat\": 38.87212, \"lon\": -94.61764}", "{\"lat\": 38.91571,
  \"lon\": -94.64835}", "{\"lat\": 38.91461, \"lon\": -94.64795}"
 )), .Names = c("timeAtSite", "location"), class = "data.frame", row.names =
 c(NA, -3L))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM