Skip to content

Instantly share code, notes, and snippets.

@cherfychow
Last active July 1, 2024 16:08
Show Gist options
  • Save cherfychow/5473d5ba1d4ceb2fab68722373ad5ed1 to your computer and use it in GitHub Desktop.
Save cherfychow/5473d5ba1d4ceb2fab68722373ad5ed1 to your computer and use it in GitHub Desktop.
## Function if coordinates are ever in degree minutes seconds
# angle input can read these formats
# 00º 00" 00
# 00 00 00
# 00º00"00
angle2dec <- function(angle) {
angle <- as.character(angle)
if (sum(str_detect(angle, '\\s*[:upper:]$')+0) > 0) {
angle <- str_remove(angle, '\\s*[:upper:]$')
warning("You passed coordinates containing N, E, S, or W. Stringr may have accounted for it but double check your outputs")
}
# use punctuation marks and symbols that aren't decimal points to split degrees minutes seconds apart
x <- do.call(rbind, str_split(angle, '[^\\d\\.]'))
if (ncol(x) == 3) {
x <- apply(x, 1L, function(y) {
y <- as.numeric(y)
y[1] + y[2]/60 + y[3]/3600
})
} else {
x <- apply(x, 1L, function(y) {
y <- as.numeric(y)
y[1] + y[2]/60
})
}
return(x)
}
@AlbanSagouis
Copy link

The ropensci/parzer package offers this functionality and it also checks if there is a W or S in the string to give negative numeric decimal coordinate and it automatically detects and supports many special characters for the splitting, not only .

@cherfychow
Copy link
Author

ah good point! I haven't used this in a while.

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