2

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")) 
 
0

1 Answer 1

2

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) 
Sign up to request clarification or add additional context in comments.

9 Comments

Hey, thank you for your quick answer! Does this solution also work in my case because i already have a dataframe with quite a lot columns and i need to change it in there?
@Amy I guess you are only interested in changing the state column, right? If that is the cause it should work as I m only extracting the column and assigning it back. Here, the trick is to match the values in the 'state' with a named vector and get the corresponding values of that vector
@Amy Not sure what is the case. Do you have the state column as factor? Check the class(df1$state) of your data? In that case, you need with(df1, tolower(setNames(state.name, state.abb)[as.character(state)]))
You are right, i want to turn the state abbreviation into the statename. i have tried it and somehow it turns my whole df into only this variable. Maybe i am on the wrong track
@Amy If you check my code, I am only extracting the column named 'state' and assigning it back. So, not sure how the whole data is changed
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.