Transform coordinates format in R

28 Views Asked by At

Is there any R package that can help me transform coordinate columns from one format to another?? I have a data frame with coordinates in columns like this:

head(tracksFKt240108) Timestamp Latitude NorS Longitude EorW 1 2024-01-08T00:00:00.481692Z 3302.013 S 7136.339 W

I need the coordinates to be in decimal degrees like -33.033548, -71.605647 I need to keep data in a data frame. I don't want to transform into a spatial object.

Thanks

The database comes from a TXT file, so I'm not sure if I have to first join some columns together, such as the columns "Latitude" and "NorS", so the numbers and the "S" are in the same column. Then I don't know if these columns need to be transformed into a certain format to be recognized as coordinates, and then be transformed from one format to another?

1

There are 1 best solutions below

0
Grzegorz Sapijaszko On

Something like (it's just substring operations and coercing to numerals):

a <- data.frame(
  lat = c("3302.013 S", "4402.013 N"),
  lon = c("7136.339 W", "5536.339 E")
)

a |>
  dplyr::mutate(
    lat_dir = substr(lat, nchar(lat), nchar(lat)),
    lat = ifelse(lat_dir == "S", 
                 -1 * as.numeric(substr(lat, 1, nchar(lat)-2))/100,
                 as.numeric(substr(lat, 1, nchar(lat)-2))/100),
    lon_dir = substr(lon, nchar(lon), nchar(lon)),
    lon = ifelse(lon_dir == "W", 
                 -1 * as.numeric(substr(lon, 1, nchar(lon)-2))/100,
                 as.numeric(substr(lon, 1, nchar(lon)-2))/100)
  ) |>
  subset(select = c(lat, lon))
#>         lat       lon
#> 1 -33.02013 -71.36339
#> 2  44.02013  55.36339

Created on 2024-02-09 with reprex v2.0.2