How to create random points (1000) of raster in r

Viewed 409

I have a raster with 2803, 5303, 14864309 (nrow, ncol, ncell), I would like to create 1000 random points inside the raster and return a tiff file. My raster is :

raster2
class      : RasterLayer 
dimensions : 2803, 5303, 14864309  (nrow, ncol, ncell)
resolution : 0.008333333, 0.008333333  (x, y)
extent     : 60.85, 105.0417, 15.95833, 39.31667  (xmin, xmax, ymin, ymax)
crs        : +proj=longlat +datum=WGS84 +no_defs 
source     : C:/NPP.tif 
names      : IPSLNPP 
values     : 0, 0.9097273  (min, max)
1 Answers

You can use the following code for that

library(raster)
library(dismo)

ext <- extent(60.85, 105.0417, 15.95833, 39.31667)
raster2 <- raster(nrow = 1000, ncol = 1000, ext = ext)
raster2[] <- runif(ncell(raster2))

#To create 1000 random points
set.seed(123)
backgr <- randomPoints(raster2, 1000, ext=ext)
backgrvals <- extract(raster2, backgr)

#To plot it you can use
plot(raster2)
points(backgr, col='black')

enter image description here

Related