phsmethods
phsmethods copied to clipboard
Scottish postcode converter (function)
Proposing a function to convert postcodes to variables found in the Scottish postcode directory.
postcode_match <- function(x, group, factor = FALSE, ...){
if (length(group) > 1) stop("Please supply a group of length 1")
y <- gsub(" ", "", x, fixed = TRUE)
y <- toupper(y)
utils::data("spd_2021_1", envir = environment(), package = "phsmethods")
postcodes <- spd_2021_1[["postcode"]]
group_names <- spd_2021_1[[group]]
y <- group_names[match(y, postcodes)]
if (factor) {
x_levels <- sort(unique(group_names))
if (sum(is.na(y)) > 0) x_levels <- c(x_levels, NA_character_)
y <- factor(y, levels = x_levels, ...)
}
return(y)
}
It could work like below:
> postcode_match("G2 1AL", group = "ca2019name")
[1] "Glasgow City"
> postcode_match("G2 1AL", group = "hb2019name")
[1] "Greater Glasgow and Clyde"
> postcode_match("G2 1AL", group = "date_of_introduction")
[1] "2011-05-03"
> postcode_match("G2 1AL", group = "hb2019name", factor = TRUE)
[1] Greater Glasgow and Clyde
14 Levels: Ayrshire and Arran Borders Dumfries and Galloway Fife Forth Valley Grampian Greater Glasgow and Clyde Highland Lanarkshire Lothian ... Western Isles