Thursday 28 November 2019

Random sampling of raster using R?


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


library(raster)

# read in raster
rasterSource <- 'landsat.TIF'

r <- raster(rasterSource)

# convert to spatial points data frame
r.spgrd<-as(r,"SpatialPointsDataFrame")

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




Answer



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
plot(r)

Raster selection


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...