[R] converting text coordinates to decimal degrees

Barry Rowlingson B.Rowlingson at lancaster.ac.uk
Tue Jun 1 15:57:33 CEST 2004


Barry Rowlingson wrote:

>> I receive GPS readings in a text string such as
>> "0121.6723S 03643.6893E" and need the coordinates as
>> decimal degrees in two separate variables: "-1.361205"
>> and "36.728155".  How do I do this in R?

>  - this works for the single test case you've given us:

  Whoops, it doesn't. I'd forgotten that longitude degrees could be 
three digits (0-180) but latitude is only two (0-90). Fixed:

convertCoord <- function(coordString){
   bits <- strsplit(coordString," ")
   lat <- bits[[1]][1]
   lon <- bits[[1]][2]
   mdCon <- function(mdstring,nd){
     d <- as.numeric(substr(mdstring,1,nd))
     m <- as.numeric(substr(mdstring,nd+1,99))/60
     return(d+m)
   }
   latD <- mdCon(substr(lat,1,nchar(lat)-1),2)
   latSign <- ifelse(substr(lat,nchar(lat),nchar(lat))=="N",1,-1)
   lonD <- mdCon(substr(lon,1,nchar(lon)-1),3)
   lonSign <- ifelse(substr(lon,nchar(lon),nchar(lon))=="E",1,-1)
   c(lonD*lonSign, latD*latSign)
}

  > convertCoord("0121.6723S 03643.6893E")
  [1] 36.728155 -1.361205

Note this isn't vectorised - if you feed it a vector of those coordinate 
strings, it wont do the right thing.

Baz




More information about the R-help mailing list