操纵光栅值 - 通过从 R 中的范围内随机选择的比率增加其值
Manipulating raster values - increase its values by a randomly selected ratio from a range in R
我正在处理一个非常大的栅格。我想将每个像素的值随机增加其原始值的 0.3-0.5。我应该应用什么样的循环才能优雅地实现它?
下面构建的示例栅格。我的光栅是 .tif
,我不想先将其转换为矩阵,除非它是最佳解决方案?
library(raster)
## Create a matrix with random data & use image()
xy <- matrix(rnorm(400),20,20)
image(xy)
# Turn the matrix into a raster
rast <- raster(xy)
# Give it lat/lon coords for 36-37°E, 3-2°S
extent(rast) <- c(36,37,-3,-2)
# ... and assign a projection
projection(rast) <- CRS("+proj=longlat +datum=WGS84")
plot(rast)
不需要循环。您可以直接访问底层像素数据,只需向其中添加一组随机数即可:
rast2 <- rast # a copy of the existing raster
random_nums <- runif(length(rast2), min = 0.3, max = 0.5) # a set of random numbers the size of the image
rast2@data@values <- rast2@data@values * random_nums # multiply the pixel data by the random values
我正在处理一个非常大的栅格。我想将每个像素的值随机增加其原始值的 0.3-0.5。我应该应用什么样的循环才能优雅地实现它?
下面构建的示例栅格。我的光栅是 .tif
,我不想先将其转换为矩阵,除非它是最佳解决方案?
library(raster)
## Create a matrix with random data & use image()
xy <- matrix(rnorm(400),20,20)
image(xy)
# Turn the matrix into a raster
rast <- raster(xy)
# Give it lat/lon coords for 36-37°E, 3-2°S
extent(rast) <- c(36,37,-3,-2)
# ... and assign a projection
projection(rast) <- CRS("+proj=longlat +datum=WGS84")
plot(rast)
不需要循环。您可以直接访问底层像素数据,只需向其中添加一组随机数即可:
rast2 <- rast # a copy of the existing raster
random_nums <- runif(length(rast2), min = 0.3, max = 0.5) # a set of random numbers the size of the image
rast2@data@values <- rast2@data@values * random_nums # multiply the pixel data by the random values