Question

I've been playing around with the ggmap R package and I really like it's plotting features for showing geographic data. I've been trying to make simple plots of some city population data I have with the geocode function, but I can't figure out how to arrange the data in a logical fashion. As it stands, I've got data structured in a list like so

              City  Type Population
1          Detroit  city     713777
2     Grand Rapids  city     188040
3           Warren  city     134056
4 Sterling Heights  city     129699
5          Lansing  city     114297
6        Ann Arbor  city     113934

and I'd like to append "columns" with the latitude and longitude entries returned by geocode. Specifically, if the above dataframe is named Michigan, I'm grabbing coordinates with

lapply(as.vector(michigan$City), geocode)

which takes a string (in this case, a city name) and uses the Google Maps api to guess at coordinates, producing a list of lists:

[[1]]
        lon      lat
1 -83.04575 42.33143

[[2]]
        lon      lat
1 -85.66809 42.96336

[[3]]
       lon    lat
1 -83.0282 42.493

[[4]]
       lon      lat
1 -83.0302 42.58031

[[5]]
        lon      lat
1 -84.55553 42.73253

[[6]]
        lon      lat
1 -83.74304 42.28083

I'd like to append the latitude and longitude values to the michigan data frame as "columns", but because the result of my lapply is a list of lists, this is trickier than just slicing some arrays -- what's the best way to do this idiomatically in R?

Was it helpful?

Solution

It's as simple as:

cbind(your_df, geocode(your_df$City))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top