[R] Change state names to abbreviations in an irregular list of names, abbreviations, null values, and foreign provinces
Ben Bolker
bbolker at gmail.com
Sat Jan 14 17:37:47 CET 2012
David Kikuchi <dkikuchi <at> email.unc.edu> writes:
> I'm trying to create maps of reptile abundance in different states &
> counties using data from Herp.net, which provides lists of specimens
> with the places that they were found. First I would like to parse the
> list by state using 2-letter abbreviations, since I'm focusing on
> certain regions. To do this, I've been trying to create a vector
> (state2) that gives all state names as 2-letter abbreviations, using
> advice given on the thread:
> http://tolstoy.newcastle.edu.au/R/help/05/09/12136.html
>
[snip]
> state2 <- rep(NA,length(tener$State.Province))
> for(i in 1:length(tener$Institution)){
> if(tener$State.Province[i] != ''){
> if(grep(tener$State.Province[i],state.name) > 0){
> state2[i] <- state.abb[grep(tener$State.Province[i],
> state.name)]
> }
> else{
> state2[i] <- NA
> }
> }
> else{
> state2[i] <- NA
> }
> }
I think you might be looking for length(grep(...))>0 , but
is this an easier way?
state.province <- c("Massachusetts","Ontario","Cuba","","Pennsylvania")
myabbr <- state.abb[match(state.province,state.name)]
myabbr
## [1] "MA" NA NA NA "PA"
(You described your problem pretty clearly, but a reproducible
example would have been nice)
More information about the R-help
mailing list