将坐标从非常规格式的度数转换为十进制度数

use*_*427 1 r geo dataframe stringr dplyr

我正在尝试转换我的数据,以便它可以绘制在地图上。例如,数据如下所示:

# A tibble: 2 x 2
  Latitud           Longitud        
  <chr>             <chr>           
1 10º 35' 28.98'' N 3º 41' 33.91'' O
2 10º 35' 12.63'' N 3º 45' 46.22'' O
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用以下方法对其进行变异:

df %>% 
  mutate(
    Latitud = str_replace_all(Latitud, "''", ""),
    lat_edit = sp::char2dms(Latitud), "°")
Run Code Online (Sandbox Code Playgroud)

返回和错误:

Error in if (any(abs(object@deg) > 90)) return("abs(degree) > 90") : 
  missing value where TRUE/FALSE needed
In addition: Warning message:
In asMethod(object) : NAs introduced by coercion
Run Code Online (Sandbox Code Playgroud)

我想在 ggplot (或其他空间包)的地图上绘制这两个点

数据:

structure(list(Latitud = c("40º 25' 25.98'' N", "40º 25' 17.63'' N"
), Longitud = c("3º 42' 43.91'' O", "3º 40' 56.22'' O")), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -2L))
Run Code Online (Sandbox Code Playgroud)

M--*_*M-- 5

您可以使用以下自定义函数(我假设N, S, W, E。不确定O经度的含义):

angle2dec <- function(angle) {
  angle <- as.character(angle)
  angle <- ifelse(grepl("S|W", angle), paste0("-", angle), angle)
  angle <- trimws(gsub("[^- +.0-9]", "", angle))
  x <- do.call(rbind, strsplit(angle, split=' '))
  x <- apply(x, 1L, function(y) {
    y <- as.numeric(y)
    (abs(y[1]) + y[2]/60 + y[3]/3600) * sign(y[1])
  })
  return(x)
}
Run Code Online (Sandbox Code Playgroud)

应用数据:

df1[] <- lapply(df1, angle2dec)

df1
#>     Latitud  Longitud
#> 1 -40.42388  3.712197
#> 2  40.42156 -3.682283
Run Code Online (Sandbox Code Playgroud)

绘图:

library(ggplot2)

ggplot(df1, aes(x = Longitud, y = Latitud)) +
  geom_point()
Run Code Online (Sandbox Code Playgroud)

显示不同半球的轻微修改数据:

df1 <- structure(list(Latitud = c("40<U+623C><U+3E61> 25' 25.98'' S", 
                                  "40<U+623C><U+3E61> 25' 17.63'' N"), 
                      Longitud = c("3<U+623C><U+3E61> 42' 43.91'' E",
                                   "3<U+623C><U+3E61> 40' 56.22'' W")), 
                 class = c("tbl_df", "tbl", "data.frame"), 
                 row.names = c(NA, -2L))
Run Code Online (Sandbox Code Playgroud)

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