问题
I have a multi-band (20 layers) raster loaded into R as a RasterBrick using brick()
.
My plan is to normalize each band from 0 to 1 using the approach that was proposed in this thread: https://stats.stackexchange.com/questions/70801/how-to-normalize-data-to-0-1-range
Here some sample code to visualize my problem:
for(j in 1:nlayers(tif)){
min <- cellStats(tif[[j]],'min')
max <- cellStats(tif[[j]],'max')
for(i in 1:ncell(tif)){
tif[i][j] <- (tif[i][j]-min)/(max-min)
}
}
"tif" contains the raster brick. "j" is the current layer of "tif", while "i" is the current cell of layer[[i]]. I think the rest is pretty straight forward. The problem now is that it takes hours without finishing to replace a single value in a specific band. Why is it taking so long without finishing?
Cheers, Kai
回答1:
Your approach is very inefficient because you are looping over each cell individually once at a time. This takes forever for larger rasters.
You can either use the approach from Geo-sp's answer (which I also wouldn't recommend if your raster is larger) or use the clusterR
function:
norm <- function(x){(x-min)/(max-min)}
for(j in 1:nlayers(tif)){
cat(paste("Currently processing layer:", j,"/",nlayers(tif), "\n"))
min <- cellStats(tif[[j]],'min')
max <- cellStats(tif[[j]],'max')
#initialize cluster
#number of cores to use for clusterR function (max recommended: ncores - 1)
beginCluster(3)
#normalize
tif[[j]] <- clusterR(tif[[j]], calc, args=list(fun=norm), export=c('min',"max"))
#end cluster
endCluster()
}
回答2:
You can read all the layers
using the stack
function then normalizing them using:
s <- stack("Some Raster Layers")
snorm <- (s - minValue(s)) / (maxValue(s)- minValue(s))
来源:https://stackoverflow.com/questions/44266752/replace-specific-value-in-each-band-of-raster-brick-in-r