Sam
Sam

Reputation: 1492

Extracting raster values, from maximum, to cumulatively sum to x

I am trying to determine the location of raster cells that add up to a given amount, starting with the maximum value and progressing down.

Eg, my raster of 150,000 cells has a total sum value of 52,000,000;

raster1 <- raster("myvalues.asc")
cellStats(raster1,sum) = 52,000,000

I can extract the cells above the 95th percentile;

q95 <- raster1
q95[q95 < quantile(q95,0.95)] <- NA
cellStats(q95,sum) = 14,132,000

as you can see, the top 5% cells (based upon quantile maths) returns around 14 million of the original total of 'raster1'.

What i want to do is predetermine the overall sum as 10,000,000 (or x) and then cumulatively sum raster cells, starting with the maximum value and working down, until I have (and can plot) all cells that sum up to x.

I have attempted to convert 'raster1' to a vector, sort, cumulative sum etc but can't tie it back to the raster. Any help here much appreciated

S

Upvotes: 1

Views: 921

Answers (2)

Robert Hijmans
Robert Hijmans

Reputation: 47706

The below is your own answer, but rewritten such that it is more useful to others (self contained). I have also changed the %in% to < which should be much more efficient.

library(raster)

r <- raster(nr=100, nc=100)
r[] = sample(ncell(r))

rs <- sort(as.vector(r), decreasing=TRUE)
r_10m <- min( rs[cumsum(rs) < 10000000] )

test <- r 
test[test < r_10m ] <- NA
cellStats(test, sum) 

Upvotes: 3

Sam
Sam

Reputation: 1492

couldnt find the edit button.....

this is something like what i need, after an hour scratching my head;

raster1v <- as.vector(raster1)
raster1vdesc <- sort(raster1v, decreasing=T)
raster1_10m <- raster1vdesc[cumsum(raster1vdesc)<10000000]

test <- raster1
test[!test%in%raster1_10m] <- NA
plot(test)
cellStats(test,sum) = 9,968,073

seems to work, perhaps, i dunno. Anything more elegant would be ideal

Upvotes: 1

Related Questions