gavinrozzi / zipcodeR

An R package that makes working with U.S. ZIP codes painless.
https://gavinrozzi.github.io/zipcodeR/
GNU General Public License v3.0
79 stars 12 forks source link

weird behavior when using reverse_zipcode inside a mutate #27

Open adamcohen3 opened 1 year ago

adamcohen3 commented 1 year ago

When I use reverse_zipcode in a mutate, it throws an error when it encounters a repeat real zipcode (in the example, zip 96817, but notice not for 00000). I was expecting it to do a vectorized operation, but that doesn't seem to be the case. Appreciate any insights people might have.

library(dplyr)
library(zipcodeR)
df <- data.frame(id = 1:13,
                 zipcode = c("96753", "00000", "96744", "96782", "00000", "96720", "96813", "96712", "96817", "96818", "96822", "00000", "96817"))
df2 <- df %>% 
  mutate(county = reverse_zipcode(zipcode)$county)

Error in mutate(): ℹ In argument: county = reverse_zipcode(zipcode)$county. Caused by error: ! county must be size 13 or 1, not 12. Run rlang::last_trace() to see where the error occurred.

rewberl commented 4 months ago

I encountered the same issue. For future reference, this is because dplyr feeds the entire vector into the reverse_zipcode() function, and one of your ZIP codes is invalid. You can add rowwise() %>% prior to the mutate (and ungroup() afterwards to avoid weird behavior for subsequent functions), or just use a for loop to go through line by line (if, like me, you need to do additional checks on the reverse_zipcode() output, for instance that it only returns one value, or a non-NA value, etc.).