Keeping data when using mapply in R

56 Views Asked by At

I have a data frame I am applying a function to using mapply(), but my result doesn't keep certain info in the initial data frame that I would like to keep. The function I am applying across the data frame is not vectorized.

DATA FRAME

Dealer  Cities                  Zip     Radius in miles     
A       Rancho Cucamonga, CA    91730   40  
A       San Bernardino, CA      92401   40  
B       Chino, CA               91710   40  
B       Fontana, CA             92337   40  

I am applying a function that gets all zip codes in the given mile radius of the initial zip.

remotes::install_github("EAVWing/ZipRadius")

results <-  with(city_names, mapply(ZipRadius::zipRadius, 
                             as.character(`Center Zip Code`),`Radius in miles`, SIMPLIFY =FALSE ))

RESULT

The result is a large list containing a data frame for each time the function zipRadius was called.

enter image description here

enter image description here

DESIRED RESULT

Each data frame contains the zip code used by the function and the data the function generates, but I would like it to also keep the corresponding "Dealer" column associated with each initial Zip.

For example, the above data frame is generated from the zip 91730, which has a Dealer value of A.

DEALER   ZIP      Other columns generated by the function...
A        90001 
A        90002
A        90011
1

There are 1 best solutions below

0
Jacob Nordstrom On BEST ANSWER

@Onyambu gave me a great solution in the comments (source):

dplyr::left_join(city_names, dplyr::bind_rows(results, .id ='zip1'),  
                  by =c(Zip= 'zip1'))