使用R中的birk库转换为十进制度数

时间:2016-06-07 05:17:30

标签: r

我正在使用库 sp 建议herehere将度 - 分 - 秒(dms)表示转换为十进制度(dd)。

如果我使用 sp 尝试以下代码,结果就是:

loc$Lat<-sp::char2dms(loc$Lat)
  

rep(value,length.out = nrows)出错:       尝试复制“S4”类型的对象

我的数据样本如下:

    c("39d47m01s N", "15d38m08s N", "12d45m01s N", "13d17m25s N", 
    "36d34m29s N", "24d46m34s S", "11d52m39s S", "39d47m01s N", "30d52m34s N", 
    "34d59m47s S")

我需要将dms转换为dd,因为我想计算点之间的Haversine(大圆距离)。

我也愿意使用其他软件包进行转换。

我尝试使用库 birk 但它给了我一些无意义的答案,其中lat / long大于1000.在尝试birk之前,我已经将lat / long表示转换为birk接受conv_unit函数

2 个答案:

答案 0 :(得分:1)

这可能是关闭的,或许比我知识渊博的人可以参与进来,但这里也是如此。

我找到了thread from R-help mailing list (from 6 years ago),其中讨论了使用公式Decimal degrees = Degrees + (Minutes/60) + (Seconds/3600)从DMS转换为十进制度数。

使用正则表达式查找适当的元素,我构造了一个data.frame,用于应用上面提到的公式。将南方和西方的坐标乘以-1,使其为负值。

xy <- c("39d47m01s N", "15d38m08s N", "12d45m01s N", "13d17m25s N", 
  "36d34m29s N", "24d46m34s S", "11d52m39s S", "39d47m01s N", "30d52m34s N", 
  "34d59m47s S")

nxy <- data.frame(degs = as.numeric(gsub("(^\\d+)(.+$)", "\\1", xy)),
                  mins = as.numeric(gsub("(^.+d)(\\d+)(m.+$)", "\\2", xy)),
                  secs = as.numeric(gsub("(^.+m)(\\d+)(s [A-Z]$)", "\\2", xy)),
                  direction = gsub("(^.+ )([A-Z])$", "\\2", xy))

nxy$indec <- with(nxy, degs + (mins/60) + (secs/3600))

nxy[nxy$direction %in% c("W", "S"), "indec"] <- nxy[nxy$direction %in% c("W", "S"), "indec"] * -1

nxy

   degs mins secs direction     indec
1    39   47    1         N  39.78361
2    15   38    8         N  15.63556
3    12   45    1         N  12.75028
4    13   17   25         N  13.29028
5    36   34   29         N  36.57472
6    24   46   34         S -24.77611
7    11   52   39         S -11.87750
8    39   47    1         N  39.78361
9    30   52   34         N  30.87611
10   34   59   47         S -34.99639

或者,你可以让char2dms为你工作。

nxy$char2dms <- as.numeric(sp::char2dms(xy, chd = "d", chm = "m", chs = "s"))

   degs mins secs direction     indec  char2dms
1    39   47    1         N  39.78361  39.78361
2    15   38    8         N  15.63556  15.63556
3    12   45    1         N  12.75028  12.75028
4    13   17   25         N  13.29028  13.29028
5    36   34   29         N  36.57472  36.57472
6    24   46   34         S -24.77611 -24.77611
7    11   52   39         S -11.87750 -11.87750
8    39   47    1         N  39.78361  39.78361
9    30   52   34         N  30.87611  30.87611
10   34   59   47         S -34.99639 -34.99639

答案 1 :(得分:0)

我只是想通了。

即使sp::char2dms接受了名为chd, chm and chs的参数,它们应该让我们指定用于度,分和秒的分隔符,但它们似乎不起作用。

在我更改了表示坐标的格式后,该函数按预期工作。所以,我只需要确保我的坐标是sp :: char2dms默认的格式,格式如下:

15d5'52.4394" N    145d40'26.04" E

度,分和秒的分隔符分别是d,'和'。