State name to abbreviation
r
Solution
1) `grep` the full name from `state.name` and use that to index into `state.abb`:
state.abb[grep("New York", state.name)]
## [1] "NY"
1a) or using `which`:
state.abb[which(state.name == "New York")]
## [1] "NY"
2) or create a vector of state abbreviations whose names are the full names and index into it using the full name:
setNames(state.abb, state.name)["New York"]
## New York
## "NY"
Unlike (1), this one works even if "New York" is replaced by a vector of full state names, e.g. `setNames(state.abb, state.name)[c("New York", "Idaho")]`
Problem
I have a large file with a variable `state` that has full state names. I would like to replace it with the state abbreviations (that is "NY" for "New York"). Is there an easy way to do this (apart from using several if-else commands)? May be using `replace()` statement?