I'm new to R and I want to extract the max and min values of a raster and create a new object with them. I need this to be done automatically, not creating the new object by hand as I will iterate the process.
Example. My raster is "elevation":
a <- setMinMax(elevation)
a returns this:
class : RasterLayer dimensions : 2828, 2464, 6968192 (nrow, ncol, ncell) resolution : 90, 90 (x, y) extent : 388323.4, 610083.4, 5261128, 5515648 (xmin, xmax, ymin, ymax) crs : +proj=utm +zone=32 +datum=WGS84 +units=m +no_defs source : dem.tif names : dem values : 92.72564, 1541.76 (min, max)
I want to create two new objects storing the min value (b) and the maximum value (c).
1 Answer 1
You can achieve this in several ways, including taking the value directly from the raster metadata, (i.e.,) :
library(raster)
elevation <- raster('FILENAME.tif')
min1 <- elevation@data@min
max1 <- elevation@data@max
OR, equivalently
min2 <- minValue(elevation$FILENAME)
max2 <-maxValue(elevation$FILENAME)
Another option is to index the pixel values in a new raster, then take the min and max from those, which produces a more precise result but may take exponentially longer for very large rasters, (i.e.,):
a <- setMinMax(elevation)
b <- a$dem@data
c <- b@min
d <- b@max
The results of the first two methods are equivalent and different from the third, but the values are very similar and only differ because of rounding error.
-
Thanks @Kartograaf. I already tried this and I get this error: Warning message: In .local(x, ...) : min value not known, use setMinMax (That's why I used setMinMax)user66349– user663492021年09月29日 15:43:28 +00:00Commented Sep 29, 2021 at 15:43
-
Also this way does not tell me the max / min values of the elevation. If I do this: r <- raster(elevation) r <- setValues(r, 1:ncell(r)) minValue <- minValue(r) maxValue(r) = 6968192 (and I need the elevation value, 1541.76 masl in this case)user66349– user663492021年09月29日 15:47:48 +00:00Commented Sep 29, 2021 at 15:47
-
OK, try the edited code now with the addition of the setValues() function.Kartograaf– Kartograaf2021年09月29日 15:47:53 +00:00Commented Sep 29, 2021 at 15:47
-
1Thanks. I just tried and get the same result as my try (6968192), but this is the max value of the dimensions of the raster, not the max values of the elevation (I'm interested on the latter).user66349– user663492021年09月29日 15:52:03 +00:00Commented Sep 29, 2021 at 15:52
-
2The problem here is that all of your examples are based on the sample min and max. Two reliable ways to deal with returning the population (actual observed) statistics are
raster::cellStats(x, 'min', asSample=FALSE)
ormin(x[], na.rm=TRUE)
Jeffrey Evans– Jeffrey Evans2021年09月30日 00:25:09 +00:00Commented Sep 30, 2021 at 0:25