问题
I am looking to generate several random raster in a loop that I plan to store. I tried something (below) that but it does not work:
r1= raster(nrows = 1, ncols = 1, res = 0.5, xmn = -1.5, xmx = 1.5, ymn = -1.5, ymx = 1.5, vals = 0.3)
a<- 10
for (i in 1:length(a)){
values(r1[i]) = round(runif(ncell(r1[i]), 0, 1))}
Thanks for any help.
回答1:
There's a much simpler way:
library(raster)
r1 <- raster(nrows = 1, ncols = 1, res = 0.5, xmn = -1.5, xmx = 1.5, ymn = -1.5, ymx = 1.5, vals = 0.3)
rr <- lapply(1:10, function(i) setValues(r1,runif(ncell(r1))))
This gives you a list rr
with 10 random rasters.
Using lapply
is optionally, you could also use a verbose loop. But like this the rasters are stored directly in a tidy list.
回答2:
runif()
is a good approach to generate random values. the matrix()
function is a way to create a raster. I stock the raster values in a list
object.
n <- 10
x_length <- 5
y_length <- 5
raster <- list(NULL)
for (i in 1:n){
raster[[i]] <- round(
matrix(
runif(x_length * y_length , 1, 10),
x_length, y_length)
)
}
raster
来源:https://stackoverflow.com/questions/52658006/how-to-create-10-random-rasters-in-r