Generate Random Points Inside Irregular Raster Boundary Using R Code

We already have a code published here that could generate random points inside an irregular raster boundary using R. If you want another option, below is an R code to generate the same random points.

You can follow the following steps:

  1. Define the irregular raster boundary: You can define the boundary using a spatial object, such as a polygon or a SpatialPolygonsDataFrame.
  2. Determine the extent of the boundary: Use the extent function to determine the extent of the boundary. This will give you the minimum and maximum values of the x and y coordinates.
  3. Generate random points: Use the runif function to generate random values between the minimum and maximum values of the x and y coordinates. You can specify the number of points you want to generate using the n argument.
  4. Create a data frame of the random points: Create a data frame of the random points with columns for x and y coordinates.
  5. Check if the points fall within the irregular raster boundary: Use the over function from the sp package to check if the points fall within the boundary. The function will return a logical vector indicating whether each point falls within the boundary.
  6. Filter the points that fall within the boundary: Use the logical vector returned by the over function to filter the points that fall within the boundary.
    library(sp)
    
    # Define the irregular raster boundary
    boundary <- readOGR(dsn = "path/to/boundary", layer = "boundary")
    
    # Determine the extent of the boundary
    boundary_extent <- as.numeric(extent(boundary))
    
    # Generate random points
    n_points <- 100
    x_coords <- runif(n_points, min = boundary_extent[1], max = boundary_extent[2])
    y_coords <- runif(n_points, min = boundary_extent[3], max = boundary_extent[4])
    
    # Create a data frame of the random points
    points <- data.frame(x = x_coords, y = y_coords)
    
    # Check if the points fall within the irregular raster boundary
    points_in_boundary <- over(points, boundary)$ID_1 > 0
    
    # Filter the points that fall within the boundary
    points_within_boundary <- points[points_in_boundary, ]

    In this example, we assume that the boundary is stored in a shapefile, and we use the readOGR function from the rgdal package to read it in. The over function returns a vector of polygon IDs that intersect with each point. We check if the IDs are greater than 0 to determine if the points fall within the boundary. Finally, we filter the points using logical subsetting.

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    three × 2 =

    This site uses Akismet to reduce spam. Learn how your comment data is processed.