library(terra)
y <- rast(ncol=10, nrow=10, nlyr=1, vals=rep(1, each=100))
I would like to randomly assign half of the values to NA?
Is there a way to do this?
To set exactly 50% of the cells to NA
you could do
library(terra)
x <- rast(ncol=10, nrow=10, nlyr=1)
x <- init(x, "cell")
x <- spatSample(x, ncell(x), "random", as.raster=TRUE)
x <- ifel(x >= ncell(x)/2, 1, NA)
With small rasters you can also do
y <- rast(ncol=10, nrow=10, nlyr=1, vals=1)
i <- sample(ncell(y), 0.5*ncell(y))
y[i] <- NA
If you just wanted random values you could do
z <- rast(ncol=10, nrow=10, nlyr=1)
z <- init(x, runif)