Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading