Replace a random sample of elements in a matrix that contain a certain value

Problem


You want to replace values within a matrix with another value, but only at a random sample of locations where the original value occurs.

 


Solution


The following code will find the index of all locations in the matrix that have a given value, then assign a new value to a random sample of those index locations.

 

#Create an example matrix
MTX <- matrix(1:5, nrow=5, ncol=5)
 
#View the matrix
MTX
 
#Find the index of all locations where MTX==2,
#and assign a new value of 888 to a random sample of 3 of those
MTX[sample(which(MTX %in% 2), 3, replace=FALSE)] <- 888
 
#View the result
MTX
 
#Note that this can be adapted for use with raster data,
#but doesn't appear to work as-is on rasters
#Use the following to turn your raster into a matrix:
    #MyMatrix <- matrix(getValues(MyRaster))

Notes


Jason Carlisle contributed to the development of this tool.