0

I need to create an function that will:

  1. search for the pixel in a raster containing the smallest value;
  2. in the first iteration, assign all the pixels within the radius equal to raster the cell size (2.5km), a value of 1 (including the pixel with the smallest value)
  3. in the second iteration, select the pixel with the next smallest value (excluding pixels selected in step ii) and search the same radius and assign these a value of 2. This continues untill there are no more pixels left (if there are no free pixels within the radius, the selection stops)

Sounds complex but hopefully possible? Here is an example of my raster:

xy <- matrix(pnorm(900,40, 200),30,30)image(xy)
rast <- raster(xy)
# Give it lat/lon coords for 36-37°E, 3-2°S
extent(rast) <- c(36,37,-3,-2)
Joe
  • 347
  • 5
  • 20
  • Please provide some example data so that it will be easier for people to answer: see http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – nico Apr 09 '15 at 12:11
  • Nico, I have added a code upto as far as I got – Joe Apr 10 '15 at 00:12

1 Answers1

1

Perhaps you can use the below. I would not try this on very large rasters (that will take forever). But for your example it works fine --- if you do not have to do this too many times.

library(raster)
set.seed(0)
xy <- matrix(rnorm(900, 40, 200),30 , 30)
r <- raster(xy)
extent(r) <- c(36,37,-3,-2)
rorig <- r
x <- r
i <- 1
while (TRUE) {
    # cell with min value 
    m <- which.min(x)
    ## are there, and do you care about ties? Do they have the same level?
    ## If not, you can do
    ## m[1]
    ## or sample
    ## m <- sample(m, 1)
    # focal and four adjacent cells
    a <- adjacent(r, m, 4, FALSE, include=TRUE)
    # exclude those that have already been affected
    w <- which(!is.na(x[a]))
    a <- a[w]
    # assign the value
    r[a] <- i
    # set assigned cells to NA
    x[a] <- NA
    # stop when done
    if (is.na(maxValue(x))) break
    i <- i + 1
}

plot(r)
plot(rorig, r)
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
  • Excellent. On the question "are there, and do you care about ties? Do they have the same level?" Ties are allowed and would ideally be reclassed to the same level/i value. – Joe Apr 13 '15 at 20:56