maximusdooku
maximusdooku

Reputation: 5542

How can I convert Degree minute sec to Decimal in 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

Upvotes: 6

Views: 7371

Answers (3)

Steven Beaupré
Steven Beaupré

Reputation: 21641

Here's an idea using splitstackshape:

library(dplyr)
library(splitstackshape)

df %>% 
  cSplit(c("Lat", "Long"), sep = " ") %>%
  transmute(Lat = Lat_1 + Lat_2 / 60 + Lat_3 / 60^2,
            Long = Long_1 + Long_2 / 60 + Long_3 / 60^2)

Which gives:

#        Lat     Long
#1: 59.74722 151.7531
#2: 59.82444 154.8822
#3: 59.77833 150.7542

Upvotes: 3

C8H10N4O2
C8H10N4O2

Reputation: 19025

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

Upvotes: 6

Bridgeburners
Bridgeburners

Reputation: 657

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)

Upvotes: 15

Related Questions