Skip to contents

This function checks if the coordinates in a data frame are in the WGS84 format and in decimal degrees. It ensures that the latitude values are between -90 and 90, and the longitude values are between -180 and 180. If the convert_to_numeric parameter is TRUE, it attempts to convert non-numeric coordinates to numeric using as.numeric(). It also prints detailed information if verbose is set to TRUE, and returns the updated data frame with numeric coordinates.

Usage

check_coordinates(
  df,
  lat_col,
  lon_col,
  convert_to_numeric = TRUE,
  verbose = FALSE
)

Arguments

df

A data frame containing the coordinates.

lat_col

The name of the column containing latitude values.

lon_col

The name of the column containing longitude values.

convert_to_numeric

Logical. If TRUE, attempts to convert the coordinates to numeric. Default is TRUE.

verbose

Logical. If TRUE, prints detailed information about invalid and non-numeric coordinates. Default is FALSE.

Value

A list containing:

  • df: The updated data frame with latitude and longitude as numeric.

  • invalid_latitudes: Indices of latitude values that are out of range or invalid.

  • invalid_longitudes: Indices of longitude values that are out of range or invalid.

  • non_numeric_latitudes: Indices of non-numeric latitude values (if any).

  • non_numeric_longitudes: Indices of non-numeric longitude values (if any).

  • rows_changed: Number of rows with changes after attempting conversion to numeric.

Examples

# A data frame with coordinates
df <- data.frame(latitude = c("45.5", "91", NA, "invalid", "12.5"),
                 longitude = c("-123.5", "200", "text", "-100", "55"))

# A list with results
list_result <- check_coordinates(df,
 "latitude",
 "longitude",
 convert_to_numeric = TRUE,
 verbose = TRUE)
#> ### Coordinate Validation Summary ###
#> Non-numeric latitude values found at rows: 4
#> Non-numeric longitude values found at rows: 3
#> Invalid latitude values (out of -90 to 90 range) found at rows: 2
#> Invalid longitude values (out of -180 to 180 range) found at rows: 2
#> Rows with changes due to as.numeric conversion: 0