Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert Degree minute sec to Decimal in R?

Tags:

regex

r

I have this dataframe:

Lat        Long
59 44 50   151 45 11
59 49 28   154 52 56
59 46 42   150 45 15

How can I convert this into decimal columns?

lat is in dd mm ss and long is in ddd mm ss

I found a similar solution here, but couldn't adapt the regex for my case.

Converting geo coordinates from degree to decimal

like image 745
maximusdooku Avatar asked Jun 16 '15 22:06

maximusdooku


People also ask

How do you convert degrees minutes seconds to radians?

To convert degrees to radians, first convert the number of degrees, minutes, and seconds to decimal form. Divide the number of minutes by 60 and add to the number of degrees. So, for example, 12° 28' is 12 + 28/60 which equals 12.467°. Next multiply by π and divide by 180 to get the angle in radians.


2 Answers

Try this function:

angle2dec <- function(angle) {
  angle <- as.character(angle)
  x <- do.call(rbind, strsplit(angle, split=' '))
  x <- apply(x, 1L, function(y) {
    y <- as.numeric(y)
    y[1] + y[2]/60 + y[3]/3600
  })
  return(x)
}

Then you can apply it to each column in your data frame:

new_df <- apply(df, 2L, angle2dec)
new_df
          Lat     Long
[1,] 59.74722 151.7531
[2,] 59.82444 154.8822
[3,] 59.77833 150.7542

or just

df$Lat <- angle2dec(df$Lat)
df$Long <- angle2dec(df$Long)
like image 191
Bridgeburners Avatar answered Sep 29 '22 14:09

Bridgeburners


May I suggest the tidyr approach:

df <- data.frame( Lat=c("59 44 50","59 49 28","59 46 42"),
                 Long=c("151 45 11","154 52 56","150 45 15"))

library(tidyr); library(dplyr)
df %>% 
  separate(Lat, paste("lat",c("d","m","s"), sep="_") ) %>%
  separate(Long, paste("long",c("d","m","s"), sep="_" ) ) %>%
  mutate_each(funs(as.numeric)) %>%
  transmute(lat_dec=lat_d + lat_m/60 + lat_s/60^2,
            long_dec=long_d + long_m/60 + long_s/60^2)

#    lat_dec long_dec
# 1 59.74722 151.7531
# 2 59.82444 154.8822
# 3 59.77833 150.7542
like image 38
C8H10N4O2 Avatar answered Sep 29 '22 15:09

C8H10N4O2