getCell: Get grid index of each point

View source: R/manageGrid.R

getCellR Documentation

Get grid index of each point

Description

Given a grid object (Grid1d, Grid2d or Grid3d) and a matrix or dataframe of points, it returns the index of each point in the grid. For a 1d grid it is counted from min to max; for a 2d grid it is counted from xmin, ymin to xmax, ymax increasing x or y faster according to the "by" parameter of the grid; for a 3d grid it is counted from xmin, ymin, zmin to xmax, ymax, zmax increasing x or z faster according to the "by" parameter of the grid.

Usage

getCell(grid, points)

Arguments

grid

Grid1d, Grid2d or Grid3d object, made with makeGrid* function

points

vector for 1d Grid, matrix or dataframe of points for 2d 3d Grid

Value

A vector in which the i-th element represents the index of the grid cell to which the i-th point belongs

Examples

# 1. Generate random points on a plane
df_points <- data.frame(
  x = c(rnorm(n = 50000, mean = -2), rnorm(n = 50000, mean = 2)),
  y = c(rnorm(n = 50000, mean = 1), rnorm(n = 50000, mean = -1))
)

# 2. Define a grid that contains all the points generated
the_grid <- makeGrid2d(
  xmin = floor(min(df_points$x)), ymin = floor(min(df_points$y)),
  xmax = ceiling(max(df_points$x)), ymax = ceiling(max(df_points$y)),
  xcell = 50, ycell = 50, by = "v"
)

# 3. Match each point with a grid element
grid_index <- getCell(the_grid, df_points)
df_points$grid_index <- grid_index

head(df_points)


Leonardo-Bo/rgrids documentation built on July 27, 2024, 2:19 a.m.