EDIT Thanks to @user5249203 for pointing out that geocoding is best done with ggmaps' geocode call. Watch out for NA's though.
I am struggling with the apply
family in R.
I am using a function which takes in a string and returns longitude and latitude
> gGeoCode("Philadelphia, PA")
[1] 39.95258 -75.16522
I have a simple dataframe which has the names of all 52 states:
dput(state_lat_long)
structure(
list(State = structure(
c(
32L, 28L, 43L, 5L, 23L, 34L,
30L, 13L, 14L, 38L, 22L, 25L, 15L, 20L, 24L, 40L, 46L, 21L, 9L,
18L, 48L, 10L, 7L, 4L, 3L, 31L, 35L, 37L, 49L, 44L, 12L, 6L,
17L, 36L, 11L, 39L, 42L, 8L, 47L, 33L, 16L, 1L, 29L, 27L, 26L,
19L, 41L, 50L, 2L, 45L
), .Label = c(
"alabama", "alaska", "arizona",
"arkansas", "california", "colorado", "connecticut", "delaware",
"florida", "georgia", "hawaii", "idaho", "illinois", "indiana",
"iowa", "kansas", "kentucky", "louisiana", "maine", "maryland",
"massachusetts", "michigan", "minnesota", "mississippi", "missouri",
"montana", "nebraska", "nevada", "new hampshire", "new jersey",
"new mexico", "new york", "north carolina", "north dakota", "ohio",
"oklahoma", "oregon", "pennsylvania", "rhode island", "south carolina",
"south dakota", "tennessee", "texas", "utah", "vermont", "virginia",
"washington", "west virginia", "wisconsin", "wyoming"
), class = "factor"
)), .Names = "State", row.names = c(NA,-50L), class = "data.frame"
)
To practice my apply
skills, I simply want to apply gGeoCode
to each cell in the only column of the state_lat_long
dataframe.
Couldn't be much simpler.
Then what is the problem with this?
> View(apply(state_lat_long, function(x) gGeoCode(x)))
When I run this, I get:
Error in View : argument "FUN" is missing, with no default
which I don't understand, because FUN
is not missing.
So, let's try sapply
. It's supposed to be simple, right?
But what is wrong with this?
View(sapply(state_lat_long$State, function(x) gGeoCode(x)))
When I run this, I get 2 rows with 50 columns, packed with NA
s. I can't make sense of it.
Next, I tried
View(apply(state_lat_long, 2, function(x) gGeoCode(x)))
and I got
State
40.71278
-74.00594
Again, this makes no sense!
What am I doing wrong? Thanks.