[R] Change state names to abbreviations in an irregular list of names, abbreviations, null values, and foreign provinces

David Kikuchi dkikuchi at email.unc.edu
Fri Jan 13 22:51:49 CET 2012


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

However, the code provided there does not work when the original list 
includes null values and foreign provinces, like "Cusco." I've used an 
if statement to filter out null values, but names not on the list 
state.names still cause me to get the error "Error in if 
(grep(tener$State.Province[i], state.name) > 0) { :
   argument is of length zero" because grep(tener$State.Province[i], 
state.name) returns the value "integer(0)", rather than something 
friendly to an If statement.  Any thoughts on how to get around this?

Thanks,

David

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
     }
}



More information about the R-help mailing list