zipcodeR icon indicating copy to clipboard operation
zipcodeR copied to clipboard

weird behavior when using reverse_zipcode inside a mutate

Open adamcohen3 opened this issue 1 year ago • 1 comments

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.

adamcohen3 avatar May 10 '23 18:05 adamcohen3

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.).

rewberl avatar Jul 24 '24 18:07 rewberl