Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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).

share|improve this question
add comment

1 Answer

up vote 18 down vote accepted

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

share|improve this answer
This answer makes me want to learn R... –  SaultDon Nov 25 '11 at 18:21
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 Dec 11 '11 at 20:21
add comment

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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