将地理坐标从度数转换为十进制

Hom*_*map 21 gis r

我想将地理坐标从度数转换为小数,我的数据如下:

         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
Run Code Online (Sandbox Code Playgroud)

我有这个代码,但我不明白为什么它不起作用:

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]))}
Run Code Online (Sandbox Code Playgroud)

转换函数有效,但我要求循环为我做的工作的代码不起作用.

任何建议都是适当的.

Cep*_*irk 24

使用measurementsCRAN中具有单位转换功能的包,这样您就不需要自己制作:

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)
Run Code Online (Sandbox Code Playgroud)

设置data.frame后:

# 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')
Run Code Online (Sandbox Code Playgroud)

导致最终产品:

                    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
Run Code Online (Sandbox Code Playgroud)

  • 这可能是最简单的解决方案(您也可以免费获得其他坐标转换)。我只想补充一点,现在该功能已移至“ measurements”包中,而在“ birk”中已弃用。 (2认同)

Noa*_*oah 7

尝试使用库中的char2dms功能sp.它还有其他功能,可以进行十进制转换.

library("sp")
?char2dms
Run Code Online (Sandbox Code Playgroud)


And*_*rie 5

某些向量化和矩阵处理将使您的函数更简单:

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)

x
Run Code Online (Sandbox Code Playgroud)

该函数本身利用:

  • strsplit()使用正则表达式模式"[°\\.]"-这一步将字符串拆分
  • sapply 遍历向量

尝试这个:

convert<-function(x){
  z <- sapply((strsplit(x, "[°\\.]")), as.numeric)
  z[1, ] + z[2, ]/60 + z[3, ]/3600
} 
Run Code Online (Sandbox Code Playgroud)

试试吧:

convert(x$long)
[1] 9.108611 8.391944 8.111111 8.254722 8.272778 8.178056
Run Code Online (Sandbox Code Playgroud)

免责声明:我没有检查您的数学。自行决定使用。