title: R: Is it possible to sample random points from only the non-NA region of a raster layer?
body: <p>I've been attempting to randomly sample a user-defined number of points from a raster layer (e.g. any of the 24 climate variable layers, in Lambert Conformal Conic projection, from <a href="https://sites.ualberta.ca/~ahamann/data/climatewna.html" rel="nofollow noreferrer">https://sites.ualberta.ca/~ahamann/data/climatewna.html</a>) using <code>spsample</code>, within a region whose extent is defined by a polygon I generated by forming circles around a set of points and aggregating their boundaries, but cannot figure out how to only sample those portions of the raster within that region which are defined. The image below shows the raster layer and polygon I am working with:<a href="https://i.stack.imgur.com/8W2kQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8W2kQ.png" alt="enter image description here"></a></p>
  
  <p>I understand that it is possible to sample within the region and then use the raster layer as a mask to remove from the sampled points those which fall within the NA region of the layer, but, in doing this, the number of background points left over is less than that which was user-specified within the <code>spsample</code> function. This is the code I've written to complete this operation:</p>
  
  <pre><code>circles &lt;- circles(coordinate_dat_train, 150000)
  circle_polygon &lt;- polygons(circles)
  proj4string(circle_polygon) &lt;- CRS("+proj=lcc +lat_1=49 +lat_2=77 +lat_0=0 +lon_0=-95 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0")
  
  sample_mask &lt;- raster("C:/...path.../cv_NORM_6190_AHM.tif")
  r_sample &lt;- spsample(circle_polygon, 1000, type='random')
  r_sample_cells &lt;- as.data.frame(extract(sample_mask, r_sample, cellnumbers = TRUE))
  r_sample_cells &lt;- as.data.frame(r_sample_cells[!is.na(r_sample_cells$cv_NORM_6190_AHM),])
  r_sample_cells &lt;- r_sample_cells[,-2]
  r_sample_coords &lt;- xyFromCell(sample_mask, r_sample_cells, spatial = TRUE)
  </code></pre>
  
  <p>I've tried also converting the raster into a polygon using the <code>rasterToPolygon</code> function, finding the intersection of this polygon and the original, and sampling within only this intersection, but with the raster layers that I am working with being so large, the time required to complete this process is not feasible. </p>
  
  <p>Are there other ways of completing this operation, which are reasonably fast in terms of computational time? Thanks in advance!</p>