[R-sig-Geo] Add +1 to current value of a cell in a raster in R

Giacomo May Giacomo_May94 at gmx.de
Sun Jul 10 21:34:40 CEST 2016


Dear R-users,
I am trying to add +1 to the cell value of certain cells in a raster. I have the cell numbers of the cells on which I'd like to perform said computation saved in a vector. I have a working code but with a large vector and raster it takes ages:

r <- raster(ncol=5,nrow=5)
r[] <- 0
vec <- c(1,1,1,3,4,5,6,7,8,8,8,9)
for(i in 1:length(vec))
{
r[vec[i]] <- r[vec[i]] + 1
}

I have already tried to use r[vec] <- r[vec] + 1 but that doesn't work properly, it just sets the values of the cells stored in the vector to 1. Does anybody know a faster way to do this ? Thanks in advance!



More information about the R-sig-Geo mailing list