mercredi 5 juin 2019

if_else across multiple columns in R

I'm using a function (mutate_geocode) that outputs two columns of data, longitude and latitude. Because google api costs money in large quantities, I only want it to run the geocode function on areas that I do NOT already have the longitude and latitude.

library(dplyr)
problem <- tibble(location = c("Atlanta United States", "Paris France", "Rome Italy"),
lon = c(NA, 2.35, 12.49),
lat = c(NA, 48.86, 41.90))

And I want it to ultimately look like this (again, WITHOUT running the geocode over the areas that I already have:

library(dplyr)
solution <- tibble(location = c("Atlanta United States", "Paris France", "Rome Italy"),
lon = c(-84.39, 2.35, 12.49),
lat = c(33.75, 48.86, 41.90))

To get there, I've tried using if_else, but I can't seem to get it to work.

library(ggmap)
library(dplyr)
solution <- if_else(is.na(problem$lon) & is.na(problem$lat), true = mutate_geocode(problem$location), false = c(problem$lon & problem$lat))

I'm open to solutions and appreciate your time! If you could also explain your code, that will help me in the future as well. Thank you!

Aucun commentaire:

Enregistrer un commentaire