In R how to convert Longitude and Latitude to a format that can be used in ggplot2 or ggmap [closed]
Asked Answered
S

1

5

I got a raw Longitude/Latitude data whose format cannot be processed by R map. So I wonder if there are some R functions or algorithms to help me to convert those raw data into a readable format. (Maybe UTM) Here is the raw data I had:

Latitude: "32-14-23 N" "31-04-27 N" "33-45-28 N"

Longitude: "121-22-38 W" "119-30-05 W" "122-47-52 W"

I wish to convert the format as(the sample below is mock data):

Longitude: -2.748

Latitude: 53.39

Storm answered 1/6, 2015 at 19:38 Comment(4)
What's your formula for converting the raw data to those float values?Yung
That's what I am asking. Any algorithm or R packages that can help?Storm
I am asking if you can explain in words what rules you are using to convert your data? How does the raw data for longitude correspond to the -2.748 value?Yung
@Yung Just modified the question. The -2.748 value is mock data. There is no relationship between -2.748 and the raw data above. I am just using -2.748 to show the data format I want.Storm
P
17

Looks like you have data in degree / minute / second format and you want it in decimal format. You can use the char2dms function in the sp package to go from character string to a degree-minute-second object, and then use as.numeric to convert to decimal

Example:

> as.numeric(sp::char2dms("32d14'23\"N"))
[1] 32.23972
> as.numeric(sp::char2dms("121d22'38\" W"))
[1] -121.3772

Also note char2dms is looking for something like 32d14'23" N, not 32-14-23 N, so you may have to assemble the proper string. Using a magrittr pipe chain:

"32-14-23 N" %>%
  sub('-', 'd', .) %>%
  sub('-', '\'', .) %>%
  sub(' ', '" ', .) %>%
  char2dms %>%
  as.numeric
Pirnot answered 1/6, 2015 at 20:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.