Skip to content

Instantly share code, notes, and snippets.

@gyli
Last active May 9, 2018 15:08
Show Gist options
  • Save gyli/acc1410041fe2938a2f5 to your computer and use it in GitHub Desktop.
Save gyli/acc1410041fe2938a2f5 to your computer and use it in GitHub Desktop.
Convert state abbreviation into full name (or opposite)
abb2state <- function(name, convert = F, strict = F){
data(state)
# state data doesn't include DC
state = list()
state[['name']] = c(state.name,"District Of Columbia")
state[['abb']] = c(state.abb,"DC")
if(convert) state[c(1,2)] = state[c(2,1)]
single.a2s <- function(s){
if(strict){
is.in = tolower(state[['abb']]) %in% tolower(s)
ifelse(any(is.in), state[['name']][is.in], NA)
}else{
# To check if input is in state full name or abb
is.in = rapply(state, function(x) tolower(x) %in% tolower(s), how="list")
state[['name']][is.in[[ifelse(any(is.in[['name']]), 'name', 'abb')]]]
}
}
sapply(name, single.a2s)
}
# Examples:
# > abb2state(c("UT", "NC"))
# UT NC
# "Utah" "North Carolina"
#
# > abb2state(c("South Carolina", "Utah", "North Carolina"), convert=T)
# South Carolina Utah North Carolina
# "SC" "UT" "NC"
#
# > abb2state(c("South Carolina", "Utah", "NC", "Arizona"))
# South Carolina Utah NC Arizona
# "South Carolina" "Utah" "North Carolina" "Arizona"
#
# > abb2state(c("South Carolina", "Utah", "NC", "Arizona"), strict = T)
# South Carolina Utah NC Arizona
# NA NA "North Carolina" NA
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment