Skip to content

Instantly share code, notes, and snippets.

@kgturner
Created April 22, 2015 22:01
Show Gist options
  • Save kgturner/72b6dc888ab585ee80de to your computer and use it in GitHub Desktop.
Save kgturner/72b6dc888ab585ee80de to your computer and use it in GitHub Desktop.
Converting between different forms of latitude and longitude (ddm, dds, dd) in R. *Messy version direct from my code, sorry*
#latitude and longitude
#convert types and add to design files
popgps<- read.table(file.choose(), header=T, sep=",",quote='"', row.names=1) #csv of pop, lat, long
popgps<-popgps[,1:3]
popgps$Longitude<-as.character(popgps$Longitude)
popgps$Latitude<-as.character(popgps$Latitude)
#add two pops to df
popgps["SAND",1]<-"48:12.055"
popgps["SAND",2]<-"16:58.449"
popgps["SAND",3]<-"ddm"
popgps["SRG",1]<-"43:10.510"
popgps["SRG",2]<-"22:40.016"
popgps["SRG",3]<-"ddm"
write.table(popgps, file="Popgps.txt", sep="\t", quote=F)
#lat for only dms
n<-popgps[popgps$type=="dms",]
n<-within(n,{
dms<-do.call(rbind, strsplit(as.character(Latitude), ":"))
dec<-as.numeric(dms[,1])+
(as.numeric(dms[,2])+as.numeric(dms[,3])/60)/60
rm(dms)
})
head(n)
n<-n[,2:4]
colnames(n)[3]<-"Latitude"
#long for dms
n<-within(n,{
dms<-do.call(rbind, strsplit(as.character(Longitude), ":"))
dec<-as.numeric(dms[,1])+
(as.numeric(dms[,2])+as.numeric(dms[,3])/60)/60
rm(dms)
})
head(n)
n<-n[,2:4]
colnames(n)[3]<-"Longitude"
#lat for ddm
o<-popgps[popgps$type=="ddm",]
o$Longitude<-as.character(o$Longitude)
o[3,2]<-"-117: 21.495"
o<-within(o,{
ddm<-do.call(rbind, strsplit(as.character(Latitude), ":"))
dec<-as.numeric(ddm[,1])+
as.numeric(ddm[,2])/60
rm(ddm)
})
o
o<-o[,2:4]
colnames(o)[3]<-"Latitude"
#long for ddm
o<-within(o,{
ddm<-do.call(rbind, strsplit(as.character(Longitude), ":"))
dec<-as.numeric(ddm[,1])+
as.numeric(ddm[,2])/60
rm(ddm)
})
o
o<-o[,2:4]
colnames(o)[3]<-"Longitude"
#merge together
Popcoord<-rbind(n, o)
Popcoord<-rbind(Popcoord, popgps[popgps$type=="dec",])
head(Popcoord)
Popcoord<-Popcoord[,2:3]
Popcoord$Pop<-rownames(Popcoord)
rownames(Popcoord)<-NULL
write.table(Popcoord, file="Popcoord.txt", sep="\t", quote=F)
@kgturner
Copy link
Author

Started with a .csv file of population locations with mixed type of latitude and longitude. Converted them all to decimal degrees (dd), if I remember correctly. Sorry for the mess, did this ages ago.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment