Amy
Amy

Reputation: 131

Rename observations in Dataframe

i have a dataframe in R and one column is called state. In this column all us states are abbreviated e.g. NY, ME etc. Now i need to rename these values with their full name e.g. new york, maine etc. I have tried multiple functions such as rename() or revalue(), but somehow they either give me an error notification or create a new value, which is not what i intend. Attached you can find one of my multiple failures. I am very thankful for all kinds of help, since i am stuck with this since a few days. Also Happy first Advent everyone!

str(rename(zipcode_new,
            "AL"="alaska","AK"="alaska","AR"="arizona","AZ"="arizona","CA"="california","CO"="colorado","CT"="conneticut","DE"="delaware","FL"="florida","GA"="georgia","HI"="hawaii","IA"="iowa","ID"="idaho","IL"="illinois","IN"="indiana","KS"="kansas","KY"="kentucky","LA"="louisiana","MA"="massachussets","MD"="maryland","ME"="maine","MN"="minnesota","MI"="michigan","MS"="mississippi","MS"="mississippi","MO"="missouri","MT"="montana","NE"="north carolina","ND"="north dakota","NH"="new hampshire","NJ"="new jersey","NM"="new mexico","NV"="nevada","NY"="new york","OH"="ohio","OK"="oklahoma","OR"="oregon","PA"="pennsylvania","SC"="south carolina","SD"="south dakota","TN"="tennessee","TX"="texas","UT"="utah","VA"="virginia","WA"="washington","WI"="wisconsin","WY"="wyoming"))

Upvotes: 2

Views: 1245

Answers (1)

akrun
akrun

Reputation: 887128

It would be easier if we can make use of the inbuilt state.name and state.abb

df1$state <- with(df1, tolower(setNames(state.name, state.abb)[state]))

Using the OP's dataset

zipcode_new$state <- with(zipcode_new, tolower(setNames(state.name, 
             state.abb)[state]))

data

set.seed(24)
df1 <- data.frame(state = sample(state.abb, 100, replace = TRUE),
         stringsAsFactors = FALSE)

Upvotes: 2

Related Questions