Skip to content

Instantly share code, notes, and snippets.

@jdunic
Last active January 12, 2022 23:10
Show Gist options
  • Save jdunic/9adb89d9229d6e915a5a800eed364291 to your computer and use it in GitHub Desktop.
Save jdunic/9adb89d9229d6e915a5a800eed364291 to your computer and use it in GitHub Desktop.
convert character dms to decimal degrees
# Good discussion on str_extract/str_match and positive look behind
# https://stackoverflow.com/questions/35804379/stringr-str-extract-how-to-do-positive-lookbehind
dms2dec <- function(string) {
string <-
str_squish(string) %>%
str_replace_all(., "\\s", "")
values <- str_match(string, "(\\d*)[\\u00B0|˚]\\s?(\\d*\\.?\\d*?)('|′|’)\\s?(\\d*?\\.?\\d*?)[\"|″]?\\s?(N|n|E|e|S|s|W|w)")
original <- values[, 1]
degrees <- values[, 2]
minutes <- (values[, 3])
seconds <- values[, 5]
direction <- values[, 6]
degrees <- as.numeric(degrees)
minutes <- ifelse(!is.na(as.numeric(minutes)), as.numeric(minutes), 0)
seconds <- ifelse(!is.na(as.numeric(seconds)), as.numeric(seconds), 0)
dms <- degrees + minutes / 60 + seconds / 3600
dms <- ifelse(direction %in% c("N", "n", "E", "e"), 1 * dms, -1 * dms)
return(dms)
}
@jdunic
Copy link
Author

jdunic commented May 14, 2021

Still need to have some clean up and should probably use str_squish to simplify regex.

@jdunic
Copy link
Author

jdunic commented Jan 12, 2022

str_squish didn't do what I thought it did, but I kept it anyway, needed to add str_replace_all to get rid of all whitespace so I could stop worrying about it

Also had to update separators

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment