Home > other >  Abbreviation to State Name Function
Abbreviation to State Name Function

Time:10-08

I am trying to create a function to convert abbreviation to state name

Ex: CA => California

abb_to_name <- function(abbr){
  x <- state.name[str_which(state.abb, toupper(abbr))]
  return(x)
}
abb_to_name("CA")
#[1] "California"

This is what I go so far. The result is not 100% as expected. But when I pass a vector, it returns:

abb_to_name(c("CA","AL"))
#[1] "California"

However, when I apply for the data frame, I need to apply map() to get the expected result:

ex <- data.frame(STATE = c("AL", "CA", "NC", "TX", "MN")) %>% 
  mutate(NAMES = map(STATE, abb_to_name))

How can I fix the function above and the result can be return as my expectation:

OUTPUT:

abb_to_name(c("CA","AL"))
#[1] "California" “Alabama”

CodePudding user response:

It makes sense to do something like this using indexing. Unfortunately, the state names aren't indexed by the abbreviations, but it's easy to fix that:

abb_to_name <- function(abbr) {
  names(state.name) <- state.abb
  state.name[abbr]
}

abb_to_name(c("CA","AL"))
#>           CA           AL 
#> "California"    "Alabama"

This doesn't exactly match what you asked for, because it returns a named vector. This version fixes that:


abb_to_name <- function(abbr) {
  names(state.name) <- state.abb
  unname(state.name[abbr])
}

abb_to_name(c("CA","AL"))
#> [1] "California" "Alabama"

Created on 2022-10-07 with reprex v2.0.2

Edited to add: If this is going in a package, I'd only set the names once, rather than every time the function is called. For example,

# This creates a package-local copy of state.name
names(state.name) <- state.abb

abb_to_name <- function(abbr) {
  state.name[abbr]
}
  •  Tags:  
  • r
  • Related