使用tidyverse在UTM和十进制度之间转换

问题描述 投票:0回答:2

我正在使用

tidyverse
sf
包将坐标从 UTM 转换为十进制。我可以进行转换,但是在使用
uniqueID
函数后我丢失了
st_coordinates()
列。我需要保留
uniqueID
列,以便我可以将其连接到另一个数据框;有没有一种方法可以在不使用
st_coordinates()
函数的情况下提取纬度/经度?

示例

library(tidyverse)
library(sf)

dat <- data.frame(
  uniqueID = seq(1,5,1),
  UTM_X = c(305334,NA,302685,300026,298030),
  UTM_Y = c(5320733,5320926,NA,5320882,5321002)
)

dat_sf <- dat %>%
  na.omit() %>%  # removes rows with missing values
  st_as_sf(coords = c('UTM_X','UTM_Y'), crs = 32616) %>% # let's R know the UTM is in zone 16
  st_transform(crs = 4326) %>% # converts UTM to decimal degree but is now stored as an sf_POINT
  st_coordinates() # extracts the lat/lon into two columns BUT drops the uniqueID

dat_sf
#>              X        Y
#> [1,] -89.61023 48.01022
#> [2,] -89.68139 48.00992
#> [3,] -89.70818 48.01037

创建于 2023-10-31,使用 reprex v2.0.2

理想输出

dat_sf

  uniqueID      lat       lon
1        1 48.01022 -89.61023
2        4 48.00992 -89.68139
3        5 48.01037 -89.70818
r dplyr coordinates geospatial coordinate-transformation
2个回答
0
投票

需要使用

mutate(lat = st_coordinates(.)[, 2],lon = st_coordinates(.)[, 1])

dat_sf <- dat %>%
  na.omit() %>% 
  st_as_sf(coords = c('UTM_X','UTM_Y'), crs = 32616) %>% 
  st_transform(crs = 4326) %>% 
  mutate(lat = st_coordinates(.)[, 2],
         lon = st_coordinates(.)[, 1]) %>%
  data.frame() %>%
  select(!geometry)

dat_sf
#>   uniqueID      lat       lon
#> 1        1 48.01022 -89.61023
#> 4        4 48.00992 -89.68139
#> 5        5 48.01037 -89.70818

创建于 2023-10-31,使用 reprex v2.0.2


0
投票

略有不同的变化:

dat %>%
  na.omit() %>%
  st_as_sf(coords = c('UTM_X','UTM_Y'), crs = 32616) %>%
  st_transform(crs = 4326) %>%
  { bind_cols(st_drop_geometry(.), st_coordinates(.)) } %>% 
  rename(lon = X, lat = Y)
#>   uniqueID       lon      lat
#> 1        1 -89.61023 48.01022
#> 2        4 -89.68139 48.00992
#> 3        5 -89.70818 48.01037
© www.soinside.com 2019 - 2024. All rights reserved.