3

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?

6

There's the char2dms function in the sp 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:

> coords
[1] "43°46′50″N 79°24′53″W" "43°46′06″N 79°24′46″W"

You could cut and paste the separators, or extract the separators from the string, eg:

> chd = substr(coords, 3, 3)[1]
> chm = substr(coords, 6, 6)[1]
> chs = substr(coords, 9, 9)[1]

Then convert to "DMS" objects:

> cd = char2dms(coords,chd=chd,chm=chm,chs=chs)
[1] 43d46'50"W 43d46'6"W 

Once you've got those, you can convert to numeric with:

> as.numeric(cd)
[1] -43.78056 -43.76833

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 the sp 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:

> char2dms(c("23d12'8\"W"))
[1] 23d12'8"W

Run it with a vector with a latitude and then a longitude:

> char2dms(c("23d12'8\"N","23d12'8\"W"))
[1] 23d12'8"N 23d12'8"S

returns two latitude.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.