Search code examples
rdata-wrangling

How to create new column with state region in R dataframe?


I have a dataframe that contains a column with state abbreviations ie. "IA", "IL", "IN,", etc. I would like to create a new column in my dataframe that assigns each row with the corresponding region ie. "Midwest", "Northeast," etc. Is there a package or good way to do this manually/with mutate() or something similar?


Solution

  • We can use inbuilt vectors to match and replace

    df1$region <- setNames(state.region, state.abb)[df1$stateabb]
    

    -output

    > df1
      stateabb    region
    1       AL     South
    2       CO      West
    3       CT Northeast
    

    data

    df1 <- structure(list(stateabb = c("AL", "CO", "CT")), 
     class = "data.frame", row.names = c(NA, 
    -3L))