1

I have Cropscape Data Layer raster with different vegetation types. I want to only keep pixels with values 43 and/or 54. I'm doing something wrong with the reclassify() function in R's raster package.

Here is a demo raster and the reclassification table I use for reclassifying:

library(raster)
r1 <- raster(ncol=10,nrow=10)
values(r1) <- c(rep(10,10), rep(43,10), rep(44,20), rep(54,40), rep(70,20))

rcl <- matrix(data=c(-1,42,NA,43,43,1,44,53,NA,54,54,2,55,255,NA), ncol=3, byrow=T)
#also tried
#rcl <- matrix(data=c(1,42,0,43,43,1,44,53,0,54,54,2,55,255,0), ncol=3, byrow=T)

I tried

r2 = reclassify(r1, rcl, right=NA)

And I still get a bunch of zero values. In this example case, 50 zeros. I want the raster to hold only the pixels of interest, those valued 1 and 2. In this case, the raster would return the 10 pixels valued at 1 and the 40 pixels valued at 2.

I did something similar to this sometime last year and created the rasters as I wanted. I have notes, but not the complete code and it looks like I used a different reclassification table with 2 columns instead of 3 columns.

rcl <- matrix(data=c(43,1,54,2), ncol=2, byrow=T)

and

r2 = reclassify(r1, rcl, otherNA=TRUE)

But that doesn't do now what I want.

1 Answer 1

1

If you know your data are integers then you could stretch your edges to include the integers you want and not fiddle with the include.lowest and right parameters which are probably the Right Way to do this. In other words:

> rcl[,1] = rcl[,1]-0.2
> rcl[,2] = rcl[,2]+0.2

so that:

> rcl
     [,1]  [,2] [,3]
[1,]  0.8  42.2   NA
[2,] 42.8  43.2    1
[3,] 43.8  53.2   NA
[4,] 53.8  54.2    2
[5,] 54.8 255.2   NA

and then:

> r2 = reclassify(r1, rcl)
> as.matrix(r2)
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA
 [2,]    1    1    1    1    1    1    1    1    1     1
 [3,]   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA
 [4,]   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA
 [5,]    2    2    2    2    2    2    2    2    2     2
 [6,]    2    2    2    2    2    2    2    2    2     2
 [7,]    2    2    2    2    2    2    2    2    2     2
 [8,]    2    2    2    2    2    2    2    2    2     2
 [9,]   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA
[10,]   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA
1
  • Thank you. I had to change the first value of rcl to -1 instead of 1 to get all zeros out of the way.
    – John Polo
    Commented Aug 25, 2021 at 21:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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