0
votes

I wand to reclassify a raster with a for loop based on seq with reclassify function from raster package, the output of the following code is empty, I don't understand why.

#create a random raster
sam <- sample(seq(0,1,0.01), 1000*1000, replace = TRUE)
r1 <- raster(nrows = 1000, ncols = 1000, vals = sam)

#create the scale for reclassify
scale <- seq(0,1,0.2)

#the for loop
cl_r <- for (i in 1:length(scale)){
  reclassify(r1, c(scale[i], scale[i+1], scale[i+1]))
}

The output:

> cl_r
NULL

I suppose that scale[i+1] is understandable by R as scale[1+1] works.

1
Can you edit your question to state what are you trying to achieve? I can't figure that out, but what you are proposing does not seem to make sense.Robert Hijmans

1 Answers

2
votes

From your question I deduce that you have numbers between 0 and 1 and would like to bin these in groups of 0.2 (0 to 0.2, 0.2 to 0.4, etc). If so, there is a number of ways to do that.

Example data

library(raster)
r <- raster(nrows=10, ncols=10)
#values(r) <- runif(ncell(r))
values(r) <- seq(0.01, 1, .01)

The simplest approach is to use cut

x <- cut(r, seq(0,1,.2))

You can use reclassify like this

m <- cbind(seq(0,.8,.2), seq(0.2,1,.2), 1:5)
y <- reclassify(r, m)

Or an algebraic approach

z <- ceiling(r * 5)

Also if you are going to loop over scale like that, note that you get NA at the end.

scale <- seq(0,1,0.2)
for (i in 1:length(scale)) { 
    cat(scale[i], "-", scale[i+1], "\n")
}
#0 - 0.2 
#0.2 - 0.4 
#0.4 - 0.6 
#0.6 - 0.8 
#0.8 - 1 
#1 - NA 

It would be cleaner to do

for (i in 2:length(scale)) { 
    cat(scale[i-1], "-", scale[i], "\n")
}
#0 - 0.2 
#0.2 - 0.4 
#0.4 - 0.6 
#0.6 - 0.8 
#0.8 - 1 

And presumably what you intended was

rc <- r
for (i in 2:length(seq(0,1,0.2))) {
     rc <- reclassify(rc, cbind(scale[i-1], scale[i], scale[i])) 
}
rc