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

Ben Tupper btupper at bigelow.org
Sun Jul 10 23:59:16 CEST 2016


Hi,

I stub my toe on this all the time (and wish I didn't).  The behavior isn't limited to raster - the replacement operator `[` in general doesn't update the left had side like my wild imagination might allow.  It's just a function and so it must make a copy of the input.

This note seen here ?`[` sort of points out the issue... "Subassignment is done sequentially, so if an index is specified more than once the latest assigned value for an index will result."  Between that, the phase of the moon and the pass-by-value stuff my brain starts to jumble. 

On the other hand, if you have dependable indices and are simply incrementing you can leverage table() for your purpose.

x <- rep(0,5)
i <- c(1,1,1,4)
ti <- table(i)
tindex <- as.numeric(names(ti))
x[tindex] <- x[tindex] + ti

Likewise for raster

library(raster)
r <- raster(ncol=5,nrow=5)
r[] <- 0
vec <- c(1,1,1,3,4,5,6,7,8,8,8,9)
tvec <- table(vec)
tindex <- as.integer(names(tvec))
r[tindex] <- r[tindex] + tvec

I hope there are smarter/faster ways, but in the meantime it might speed things along for you.  


Ben


> On Jul 10, 2016, at 3:34 PM, Giacomo May <Giacomo_May94 at gmx.de> wrote:
> 
> 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!
> 
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Report Gulf of Maine jellyfish sightings to jellyfish at bigelow.org or tweet them to #MaineJellies -- include date, time, and location, as well as any descriptive information such as size or type.  Learn more at https://www.bigelow.org/research/srs/nick-record/nick-record-laboratory/mainejellies/



More information about the R-sig-Geo mailing list