Linking UK postcodes to their lat/long for a leaflet plot, but a missing space is stopping a few hundred their lat/long when left_join()
.
Have a df where some of the postcodes are missing the space between the first and second part of the code: should be 2 chr and 1 or 2 num in the first part (ie EH1 or FK15), and the second part 1 num and 2 chr (ie 1AD).
Want to change all the postcodes to the same then will left_join()
later to get the lat/long.
Have tried the case_when()
, if_else()
and gsub()
that was mentioned in a similar question on this site, but with no luck.
event1356 %>%
mutate(postcode = str_to_upper(postcode),
postcode = case_when(
postcode %in% "[0-9]{2}+[A-Z]{2}$" ~ " [0-9]+[A-Z]{2}$",
TRUE ~ postcode)
) %>%
filter(str_detect(postcode, pattern = "[0-9]{2}+[A-Z]{2}$"))
event1356 %>%
mutate(postcode = str_to_upper(postcode),
postcode = case_when(
postcode %in% "[0-9]{2}+[A-Z]{2}$" ~ gsub(postcode,
"(^[A-Z]{2}+[0-9])([0-9]{1}+[A-Z]{2}$)",
"\\1 \\2", postcode),
TRUE ~ postcode)
) %>%
filter(str_detect(postcode, pattern = "[0-9]{2}+[A-Z]{2}$"))
Both above made no different
event1356 %>%
mutate(postcode = str_to_upper(postcode),
postcode = if_else(str_detect(postcode,
pattern = "[0-9]+[A-Z]{2}$"),
gsub("(^[A-Z]{2}+[0-9]{1,})([0-9]{1}+[A-Z]{2}$)", "\\1 \\2"), postcode)
) %>%
filter(str_detect(postcode, pattern = "[0-9]{2}+[A-Z]{2}$"))
event1356 %>%
mutate(postcode = str_to_upper(postcode),
postcode = if_else(str_detect(postcode,
pattern = "^[A-Z]{2}+[0-9]{1,}+[0-9]+[A-Z]{2}$"),
gsub("([0-9])([0-9]+[A-Z]{2}$)", "\\1 \\2"), postcode)
) %>%
filter(str_detect(postcode, pattern = "[0-9]{2}+[A-Z]{2}$"))
Error: Problem with mutate()
column postcode
.
i postcode = if_else(...)
.
x argument "x" is missing, with no default
event1356 %>%
mutate(postcode = str_to_upper(postcode),
postcode = if_else(str_detect(postcode,
pattern = "[0-9]{2}+[A-Z]{2}$"),
gsub(postcode, "(^[A-Z]{2}+[0-9])([0-9]{1}+[A-Z]{2}$)", "\\1 \\2"), postcode)
) %>%
filter(str_detect(postcode, pattern = "[0-9]{2}+[A-Z]{2}$"))
event1356 %>%
mutate(postcode = str_to_upper(postcode),
postcode = if_else(str_detect(postcode,
pattern = "^[A-Z]{2}+[0-9]{1,}+[0-9]+[A-Z]{2}$"),
gsub(postcode, "(^[A-Z]{2}+[0-9])([0-9]{1}+[A-Z]{2}$)", "\\1 \\2"), postcode)
) %>%
filter(str_detect(postcode, pattern = "[0-9]{2}+[A-Z]{2}$"))
event1356 %>%
mutate(postcode = str_to_upper(postcode),
postcode = if_else(str_detect(postcode,
pattern = "[0-9]+[A-Z]{2}$"),
gsub(postcode, "(^[A-Z]{2}+[0-9]{1,})([0-9]{1}+[A-Z]{2}$)",
"\\1 \\2", gsub(" ", "", postcode)), postcode)
) %>%
filter(str_detect(postcode, pattern = "[0-9]{2}+[A-Z]{2}$"))
Warning: Problem with mutate()
column postcode
.
i postcode = if_else(...)
.
i argument 'pattern' has length > 1 and only the first element will be used
Example of the df:
postcode <- c("EH1 1AD", "EH1 1AE", "EH13 5ED", "GA3 9RD", "FK15 8ED", "Fk81tu", "FK159DY", "69005", "FK54UP", "FK10 WTF", "FK94DQ", "FK102ET", "FK159JE", "FK95HQ", "PH20BL")