Last active
January 13, 2017 22:40
-
-
Save ashleylester/b806d82d1d61edbfe0cc551f97219989 to your computer and use it in GitHub Desktop.
Easy way to iterate over a data frame and append multiple columns from a function returning a data frame
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## An example of iterating over a data frame using the apply family and | |
## the tidyverse, appending multiple columns to a resultset. | |
library(tidyverse) | |
library(ggmap) | |
latLong <- data.frame(long= c(78.0422, -0.1246, 131.035904, 122.3493), | |
lat = c(27.1750, 51.5007, -25.344646, 47.6205), | |
name = c("Taj Mahal", "Big Ben", "Uluru", "Space Needle")) | |
## Address details are found by a reverse geocode lookup. | |
## The function returns a data frame. | |
results <- revgeocode(c(78.0422, 27.1750), output = "more") | |
## We want to return an arbitrarily large set of results | |
## by applying the function to the vectors containing | |
## the latitude and longitude, writing the results | |
## back to the data frame. | |
## If we want to bring back a single value, we can use mapply. | |
getLocality <- function(long, lat) { | |
locality <- revgeocode(c(long, lat), output = "more") | |
locality <- locality$locality | |
return(locality) | |
} | |
localities <- mapply(getLocality, latLong$long, latLong$lat) | |
## We can use the function to return the values to the data frame | |
## as a new column. | |
latLong$locality <- mapply(getLocality, latLong$long, latLong$lat) | |
## We can also use dplyr. | |
latLong <- latLong %>% | |
rowwise() %>% | |
mutate(dplyrLocality = getLocality(long, lat)) | |
## What about if we want to write back all of the result set? | |
getAddress <- function(long, lat) { | |
address <- revgeocode(c(long, lat), output = "more") | |
return(address) | |
} | |
## What is the best way to write the whole data frame back to the | |
## latLong data frame as multiple new columns? We can use the map2_df | |
## function from the purrr package, which returns a data frame. | |
df <- map2_df(latLong$long, latLong$lat, getAddress) | |
result <- data.frame(latLong,df) | |
## Copy the script into your R console and try it out! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment