Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 231
Ye Xu Avatar asked Dec 04 '22 03:12

Ye Xu


1 Answers

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
like image 63
arvi1000 Avatar answered Dec 28 '22 08:12

arvi1000