Converting geo coordinates from degree to decimal

r gis
Homap picture Homap · Jan 18, 2013 · Viewed 22.3k times · Source

I want to convert my geographic coordinates from degrees to decimals, my data are as follows:

         lat     long
105252 30°25.264 9°01.331
105253 30°39.237 8°10.811
105255 31°37.760 8°06.040
105258 31°41.190 8°06.557
105259 31°41.229 8°06.622
105260 31°38.891 8°06.281

I have this code but I can not see why it is does not work:

convert<-function(coord){
tmp1=strsplit(coord,"°")
tmp2=strsplit(tmp1[[1]][2],"\\.")
dec=c(as.numeric(tmp1[[1]][1]),as.numeric(tmp2[[1]]))
return(dec[1]+dec[2]/60+dec[3]/3600) 
} 
don_convert=don1
for(i in 1:nrow(don1)){don_convert[i,2]=convert(as.character(don1[i,2]));              don_convert[i,3]=convert(as.character(don1[i,3]))}

The convert function works but the code where I am asking the loop to do the job for me does not work.

Any suggestion is apperciated.

Answer

CephBirk picture CephBirk · May 12, 2016

Use the measurements package from CRAN which has a unit conversion function already so you don't need to make your own:

x = read.table(text = "
   lat     long
105252 30°25.264 9°01.331
105253 30°39.237 8°10.811
105255 31°37.760 8°06.040
105258 31°41.190 8°06.557
105259 31°41.229 8°06.622
105260 31°38.891 8°06.281",
header = TRUE, stringsAsFactors = FALSE)

Once your data.frame is set up then:

# change the degree symbol to a space
x$lat = gsub('°', ' ', x$lat)
x$long = gsub('°', ' ', x$long)

# convert from decimal minutes to decimal degrees
x$lat = measurements::conv_unit(x$lat, from = 'deg_dec_min', to = 'dec_deg')
x$long = measurements::conv_unit(x$long, from = 'deg_dec_min', to = 'dec_deg')

Resulting in the end product:

                    lat             long
105252 30.4210666666667 9.02218333333333
105253         30.65395 8.18018333333333
105255 31.6293333333333 8.10066666666667
105258          31.6865 8.10928333333333
105259         31.68715 8.11036666666667
105260 31.6481833333333 8.10468333333333