parseCoordinates.R (1035B)
1 #' Parse funky lat/long representations. 2 #' 3 #' @param coord A character vector representing latitude or longitude data. 4 #' @return A numeric vector of (decimal) coordinate info, negative for west and 5 #' south coordinates. 6 #' 7 #' @details This currently only handles coordinates in the format DD-DD-DDL. 8 #' 9 #' @export 10 parseCoordinates <- function(coord) { 11 if (!is.character(coord)) { 12 stop("Only dealing with character vectors.") 13 } 14 15 # Get the direction 16 direction <- gsub("[^NSEWnsew]", "", coord) 17 direction[is.na(direction) | nchar(direction) == 0] <- "1" 18 direction <- unname(vapply(direction, switch, numeric(1), S = -1, W = -1, 1)) 19 20 # Continue parsing the coord 21 coord <- gsub("[^[:digit:][:punct:]]", "", coord) 22 combineParts <- function(x) { 23 n <- as.numeric(x) 24 if (length(n) != 3) { 25 d <- NA 26 } else { 27 d <- n[1]+n[2]/60+n[3]/3600 28 } 29 return(d) 30 } 31 coord <- direction * vapply(strsplit(coord, "[[:punct:]]"), 32 combineParts, numeric(1)) 33 return(coord) 34 }