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?
CodePudding user response:
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))
CodePudding user response:
yes, R has two packages - state.abb has all the state abbreviations, state.region has their regions. You don't need mutate, just cbind