Is there a straightforward way of randomly sampling a raster so that the output of the process is a raster?

I'm using an example that I found on the r-sig-geo list and I have also tried the sampleRandom function in the raster package. Both of these approaches produce an output that I am not certain how to transform into a raster. I was not able to find an approach after searching for several combinations of "SpatialPointsDataFrame raster".


# read in raster
rasterSource <- 'landsat.TIF'
r <- raster(rasterSource)

# convert to spatial points data frame

# elminate NA values
r.spgrd = r.spgrd[!is.na(r.spgrd[[1]]),] 

# sample points
selectedPoints = sample(1:length(r.spgrd[[1]]), 1000)
r.sampled = r.spgrd[selectedPoints,]

# try to make spgrd into a raster
r.test <- raster(r.sampled)

When I run r.test I get the output:

class       : RasterLayer 
dimensions  : 10, 10, 100  (nrow, ncol, ncell)
resolution  : 28617, 14766  (x, y)
extent      : 1838505, 2124675, 2328685, 2476345  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=aea +lat_1=29.5 +lat_2=45.5 +lat_0=23 +lon_0=-96 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0 
values      : none

So that the following line which tries to write a raster produces the message:

# write out as ascii file
writeRaster(r.test, filename="test1.ASC", datatype="ascii", overwrite=TRUE)

Error: hasValues(x) is not TRUE

My main objective is to produce some type of raster after the sampling process. I'm also fine with just changing the values within my raster (I'm just not certain how to do that).

2 Answers 2


You can adapt examples from the Raster package vignette, section 5.2. Here's one way:

r <- raster(ncol=30,nrow=20)
r[] <- 1:(30*20)              # Raster for testing
#plot(r)                      # (If you want to see it)
r[runif(30*20) >= 0.30] <- NA # Randomly *unselect* 70% of the data

Raster selection

  • 10
    This answer makes me want to learn R...
    – SaultDon
    Commented Nov 25, 2011 at 18:21
  • 2
    This may be extremely obvious, but it took me some time to realize that the value of any cell can be referenced by r[r "condition"]. So if you want to set all value of the raster that are 100 to be 1 you can write r[r == 100] <- 1. Thanks @whuber - extremely useful example!
    – djq
    Commented Dec 11, 2011 at 20:21
  • @whuber Any clue why the Error: hasValues(x) is not TRUE popped up?
    – csheth
    Commented Jun 20, 2015 at 20:05

You can use the sampleRandom function:

r <- raster(ncol=30,nrow=20)
r[] <- 1:ncell(r)

x <- sampleRandom(r, ncell(r)*.3, asRaster=TRUE)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.