This function returns the cell index from a grid file based on the provided extent or coordinates. If neither extent nor coordinates are provided, the full grid will be returned. If both extent and coordinates are provided, the function will stop and ask for only one of them. The extent should be a vector of length 4 in the form c(lonmin, lonmax, latmin, latmax). If the extent is not in the correct form, the function will swap the values to correct it.

get_cellindex(grid_filename, extent = NULL, coordinates = NULL)

Arguments

grid_filename

A string representing the grid file name.

extent

A numeric vector (lonmin, lonmax, latmin, latmax) containing the longitude and latitude boundaries between which values included in the subset.

coordinates

A list of two named (lon, lat) numeric vectors representing the coordinates.

Value

The cell index from the grid file based on the provided extent or coordinates.

Details

The function reads a grid file specified by grid_filename and creates a data frame with columns for longitude, latitude, and cell number. The cell number is a sequence from 1 to the number of rows in the data frame.

If an extent is provided, the function filters the cells to include only those within the specified longitude and latitude range. The extent should be a numeric vector of length 4 in the form c(lonmin, lonmax, latmin, latmax).

If a list of coordinates is provided, the function filters the cells to include only those that match the specified coordinates. The coordinates should be a list of two character vectors representing the longitude and latitude values as for subset().

If both extent and coordinates are provided, the function will stop and ask for only one of them. If neither extent nor coordinates are provided, the function will return the cell numbers for all cells in the grid.

The function also includes checks for input types and values, and gives specific error messages for different error conditions. For example, it checks if the grid_filename exists, if the extent vector has the correct length, and if the coordinates list contains two vectors of equal length.

Examples

if (FALSE) {
get_cellindex(
  grid_filename = "my_grid.bin.json",
  extent = c(-123.25, -122.75, 49.25, 49.75) # (lonmin, lonmax, latmin, latmax)
)
get_cellindex(
  grid_filename = "my_grid.bin.json",
  coordinates = list(lon = c(-123.25, -122.75), lat = c(49.25, 49.75))
)
}