Lily Nature
Lily Nature

Reputation: 695

How to change the proportion of raster gridcell values

In a sample raster r how can I change the proportion of pixel value 84 to 25% from 9% as you see in per_84? I.e. I want to increase the number of pixels with pixel value 84 and decrease the number of pixels with other values with the following condition.

The increase of the proportion of 84 from 9% to 25% comes as follows:9% (of 84) is already in the raster. Out of the remaining 16% 6% comes from pixel value 90, 5% from pixel value 85, and the remaining 5% comes from pixel value 80.

set.seed(200)
r <- raster(ncol=10,nrow=20)
r[] <- sample(80:90, 200, replace=T)    
plot(r)   
getValues(r)
no_cell_val84 <- cellStats(r,function(x,...) sum(x==84)) 
no_cell_val84

no_grid_cell <- ncell(r)
no_grid_cell

per_84 <- (no_cell_val84/no_grid_cell)*100
per_84

Upvotes: 0

Views: 34

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47481

Here with "terra" (the replacement of the "raster" package)

Example data

library(terra)
set.seed(200)
r <- rast(ncol=10,nrow=20)
values(r) <- sample(80:90, 200, replace=TRUE)
r[13:14,] <- NA    

The number of cells with value v (84)

v <- 84
nv <- global(r==v, sum, na.rm=TRUE)[[1]] 
nv 
#[1] 18

How many cells do we need to add?

nc <- ncell(r)
add <- (0.25 * nc) - nv
add 
#[1] 32

Start with a sample that is larger than add because we need to remove the cells that already are 84.

i <- sample(nc, 2*add)
rv <- r[i]
# remove cells that have value v
i <- i[-which(rv == v)]
# subset to the number we need
if (length(i) >= add) {
   i <- i[1:add]
} else {
   print("the sample is too small")
}
head(i)
#[1]  60  88  39  22 146  10

Now update the values and verify.

r[i] <- v

global(r==v, sum, na.rm=TRUE)[[1]] 
#[1] 50

Upvotes: 0

Related Questions