-1

How do I generate 5 random rasters with values within defined bounds (different for each raster), and with pixel values summing up to 1?

Here are the bounds

xmin <- c(0, 0, 0, 0, 0)
xmax <- c(26.0, 78.6, 14.4, 39.4, 70.8)

Can I also follow the distribution of values from a second raster for each of the random rasters?

jmutua
  • 290
  • 1
  • 12
  • What's your thinking with pixel values summing up to `n`? – Chris Nov 07 '22 at 19:31
  • I need to set up a montecarlo simulation with `5` input rasters, and for each simulation values per pixel should sum up to `1` – jmutua Nov 07 '22 at 21:33
  • These are not reasonable bounds if you want the sum of the sampled values to be 1. You would expect that they would be between 0 and 0.3 or thereabouts – Robert Hijmans Nov 08 '22 at 21:03

2 Answers2

1

Imagining the rasters would have different min/max,

set.seed(42)
rand_1 <- terra::rast(array(sample(2:9, 100, replace = TRUE), dim=c(10,10,1), dimnames= NULL))
rand_2 <- terra::rast(array(sample(6:11, 100, replace = TRUE), dim=c(10,10,1), dimnames= NULL))
rand_3 <- terra::rast(array(sample(1:7, 100, replace = TRUE), dim=c(10,10,1), dimnames= NULL))
rand_4 <- terra::rast(array(sample(5:10, 100, replace = TRUE), dim=c(10,10,1), dimnames= NULL))
rand_5 <- terra::rast(array(sample(1:20, 100, replace = TRUE), dim=c(10,10,1), dimnames= NULL))
rand_5_diff_min_max <- c(rand_1, rand_2, rand_3, rand_4, rand_5)
rand_5_diff_min_max
class       : SpatRaster 
dimensions  : 10, 10, 5  (nrow, ncol, nlyr)
resolution  : 1, 1  (x, y)
extent      : 0, 10, 0, 10  (xmin, xmax, ymin, ymax)
coord. ref. :  
source(s)   : memory
names       : lyr.1, lyr.1, lyr.1, lyr.1, lyr.1 
min values  :     2,     6,     1,     5,     1 
max values  :     9,    11,     7,    10,    20

where same min/max could be achieved with

rand_5 <- terra::rast(array(sample(2:9, 500, replace = TRUE), dim=c(10,10,5), dimnames= NULL))

If you have dimnames in mind, put them in a dimnames = list('. Still don't know your thinking on pixels adding to n.

Chris
  • 1,647
  • 1
  • 18
  • 25
1

You could do

library(terra)
x <- rast(ncol=10, nrow=10)
xmin <- 1:5  / 10
xmax <- 6:10 / 10
x <- rast(sapply(1:5, \(i) init(x, runif(ncell(x), min=xmin[i], max=xmax[i]))))

x <- x / sum(x)

Of course, after this the ranges of the values have changed. But this shows how to do things with raster data. Your real question is probably "how do I take five random numbers that are within certain bounds (different for each number), and that add up to 1". Once you have figured that out, the raster stuff is easy (replace init with your function). That is a bit tricky, and it would be helpful if provide an example of the bounds that you have in mind.

Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
  • I have just added the bounds in the question. Can I also follow the distribution of values from a second raster for each of the random rasters? – jmutua Nov 08 '22 at 16:51