I am reading a raster file using both terra and raster package
library(raster)
library(terra)
fl_terra <- terra::rast('my_raster.tif')
fl_raster <- raster::raster('my_raster.tif')
fl_terra
class : SpatRaster
dimensions : 157450, 327979, 1 (nrow, ncol, nlyr)
resolution : 0.0002777778, 0.0002777778 (x, y)
extent : -142.4107, -51.30541, 41.12569, 84.86181 (xmin, xmax, ymin, ymax)
coord. ref. : lon/lat WGS 84 (EPSG:4326)
source : xxxx.tif
categories : DepthBand
name : DepthBand
min value : 0.0m <= x <= 0.3m
max value : x > 9.0m
fl_raster
class : RasterLayer
dimensions : 157450, 327979, 51640293550 (nrow, ncol, ncell)
resolution : 0.0002777778, 0.0002777778 (x, y)
extent : -142.4107, -51.30541, 41.12569, 84.86181 (xmin, xmax, ymin, ymax)
crs : proj=longlat datum=WGS84 no_defs
source : xxxx.tif
names : DepthBand
values : 1, 6 (min, max)
Why is reading the same file using the two packages showing different values?
If I open the same file in QGIS, the legend displays the values present in the fl_raster
i.e. using the raster
package.
CodePudding user response:
The file has categorical values. fl_terra
tells you that:
categories : DepthBand
And it also properly shows the (alphabetical) range of the categories (and it also uses them in the legend when using plot, and returns them when extracting cell values).
name : DepthBand
min value : 0.0m <= x <= 0.3m
max value : x > 9.0m
If you do not care about the categories, you can remove them with
levels(fl_terra) <- NULL
In contrast, fl_raster
shows the numerical codes that are used to represent the categories (because the raster files can only store numeric cell values).
values : 1, 6 (min, max)
That makes it look like you have numeric values. But that is not the case.
The situation is similar to having a factor in R
f <- as.factor(c("red", "blue", "green"))
"terra" would show the category labels
f
#[1] red blue green
#Levels: blue green red
Whereas "raster" would show the equivalent of
as.integer(f)
#[1] 3 1 2