transform_coordinates: Transform x-y coordinates from 'data.frame' columns.

View source: R/transform_coordinates.R

transform_coordinatesR Documentation

Transform x-y coordinates from data.frame columns.

Description

This function extracts x-y coordinates from a data.frame by means of the given coordinate reference system (CRS), transforms them to the new CRS and assign them back to the data.frame columns.

Usage

transform_coordinates(df, col_x, col_y, crs_input, crs_output)

Arguments

df

A data.frame with a x and y coordinate column.

col_x, col_y

Column names or positions of the x and y column. They are passed to vars_pull. These arguments are passed by expression and support quasiquotation (you can unquote column names or column positions).

crs_input

Projection string of class CRS-class (sp compatible) or crs-class (sf compatible) defining the current CRS.

crs_output

Projection string of class CRS-class (sp compatible) or crs-class (sf compatible) defining the CRS to convert to.

Value

A data.frame with the same columns, but transformed coordinates for the x and y column values.

See Also

Other GIS_utilities: guess_crs(), plot_coordinates_on_map()

Examples

library(sf)
data_pts <- data.frame(
  id = c(1, 2),
  lat = c(51.23031, 50.76931),
  lon = c(5.083980, 3.829593),
  stringsAsFactors = FALSE
)

# CRS-class (use sp package)
if (requireNamespace("sp")) {
  sp_crs1 <- sp::CRS("+init=epsg:4269")
  sp_crs2 <- sp::CRS("+init=epsg:3857")
  transform_coordinates(data_pts,
    col_x = "lon", col_y = "lat",
    crs_input = sp_crs1, crs_output = sp_crs2
  )
}
# crs-class (use sf package)
sf_crs1 <- st_crs(4269)
sf_crs2 <- st_crs(3857)
transform_coordinates(data_pts,
  col_x = "lon", col_y = "lat",
  crs_input = sf_crs1, crs_output = sf_crs2
)

if (requireNamespace("sp")) {
  # input projection is CRS-class (sp) and output projection crs-class (sf)
  transform_coordinates(data_pts,
    col_x = "lon", col_y = "lat",
    crs_input = sp_crs1, crs_output = sf_crs2
  )
  # input projection is crs-class (spf and output projection CRS-class (sp)
  transform_coordinates(data_pts,
    col_x = "lon", col_y = "lat",
    crs_input = sf_crs1, crs_output = sp_crs2
  )
}

# use names (character) of x-y columns
transform_coordinates(data_pts,
  col_x = "lon", col_y = "lat",
  crs_input = sf_crs1, crs_output = sf_crs2
)
# use NSE of x-y columns
transform_coordinates(data_pts,
  col_x = lon, col_y = lat,
  crs_input = sf_crs1, crs_output = sf_crs2
)
# use position of x-y columns
transform_coordinates(data_pts,
  col_x = 3, col_y = 2,
  crs_input = sf_crs1, crs_output = sf_crs2
)


inbo/inborutils documentation built on Nov. 23, 2023, 4:42 a.m.