I have a vector of DMS coordinates similar in format to the following:
coords <- c("43°46′50″N 79°24′53″W", "43°46′06″N 79°24′46″W")
and I would like to convert them into two numeric decimal vectors for latitude and longitude to eventually mark them in leaflet
.
coords_lat <- c(43.780556, 43.768333)
coords_lon <- c(-79.414722, -79.412778)
My question is: Is there a function available out there in R
that does this conversion automatically, or would I need to rely on regex and some outside tool to convert them myself?
Best Answer
There's the
char2dms
function in thesp
package that will convert this format, and you'll have to give it the right separator characters. Your example has some interesting separators that I don't have on my keyboard:You could cut and paste the separators, or extract the separators from the string, eg:
Then convert to "DMS" objects:
Once you've got those, you can convert to numeric with:
To get the lat and the long you'll probably have to split your strings and then use
char2dms
, unless there's something else in thesp
package....Note that you can only run
char2dms
on a vector of longs or lats - if you mix them up it fails, interpreting them as whatever the first one is, it seems:This is a longitude, West:
Run it with a vector with a latitude and then a longitude:
returns two latitude.