Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquently change many raster cell values in R

I have a Landfire Existing Vegetation dataset (http://www.landfire.gov/), which I have projected and cropped to my study site. The raster has ~12,000,000 cells. The cell values represent a particular vegetation type, and the values range from 16:2200. All of those values are not represented in my study area (i.e. values jump from 20 to 1087).

As many of the pixels' values can be lumped together into one classification for my purposes (e.g. different shrub communities into one class), I wanted to reset the values of the raster to simpler values (1:11). This will facilitate easy extraction of data from other rasters by vegetation type and ease of plotting the classification map. I have a working code, but it requires a ton of typing to change all 61 of the values I need to change. Here's what I did:

#===============================
############Example#############
#===============================

library(raster)
r <- raster(nrows=30, ncols=10, xmn=0, xmx=10)
r[] <- rep(10:19, 30)

r.omance <- function(x){
            x[x==10] <- 1; x[x==11] <- 1; x[x==12] <- 1
            x[x==13] <- 1; x[x==14] <- 1; x[x==15] <- 1

            x[x==16] <- 2; x[x==17] <- 2; x[x==18] <- 2
            x[x==19] <- 2
            return(x)}

reclass <- calc(r, fun = r.omance) 

Does anyone know of an easier way to go about this? You can imagine the typing to change 61 values, especially since x[x==16:20] <- 1 was producing an error, so every value had to be typed out separately. As I said, my code works. But I just want to become a better R coder.

Thanks.

like image 821
vitale232 Avatar asked Dec 11 '22 15:12

vitale232


2 Answers

You could use %in%:

x %in% c(1,4,3:10)

This:

x[x==10] <- 1; x[x==11] <- 1; x[x==12] <- 1
x[x==13] <- 1; x[x==14] <- 1; x[x==15] <- 1

would reduce to:

x[x %in% 10:15]
like image 121
Paul Hiemstra Avatar answered Jan 03 '23 05:01

Paul Hiemstra


I would use the reclassify function

library(raster)
r <- raster(nrows=30, ncols=10, xmn=0, xmx=10)
r[] <- rep(10:19, 30)
rc <- matrix(c(10,15,1,16,19,2), ncol=3, byrow=TRUE)
x <- reclassify(r, rc, right=NA)
like image 40
Robert Hijmans Avatar answered Jan 03 '23 06:01

Robert Hijmans