The error hasValues(x) is not TRUE
is returned when the RasterLayer has no values. The problem in the operations lies in the use of the raster
function to transform a RasterBrick to a RasterLayer. Using raster(brick_name)
just creates an empty RasterLayer with the dimensions (nrow, ncol, ndim) of the RasterBrick, but loses the values because raster
doesn't know which layer to use from the RasterBrick in the new RasterLayer.
The documentation for the raster
function says:
In many cases, e.g. when a RasterLayer is created from a file, it
does (initially) not contain any cell (pixel) values in (RAM)
memory, it only has the parameters that describe the RasterLayer.
but doesn't go into detail which of the many cases do this! You hit one of them. Here's a fully reproducible example that makes a brick from an array:
> b = brick(array(1:(4*5*6),c(4,5,6)))
> b
class : RasterBrick
dimensions : 4, 5, 20, 6 (nrow, ncol, ncell, nlayers)
resolution : 0.2, 0.25 (x, y)
extent : 0, 1, 0, 1 (xmin, xmax, ymin, ymax)
coord. ref. : NA
data source : in memory
names : layer.1, layer.2, layer.3, layer.4, layer.5, layer.6
min values : 1, 21, 41, 61, 81, 101
max values : 20, 40, 60, 80, 100, 120
so my brick b
has values but...
> raster(b)
class : RasterLayer
dimensions : 4, 5, 20 (nrow, ncol, ncell)
resolution : 0.2, 0.25 (x, y)
extent : 0, 1, 0, 1 (xmin, xmax, ymin, ymax)
coord. ref. : NA
raster(b)
doesn't.
What's the reasoning for this? I suspect its that if:
> r1 = raster(r)
created a raster r1
that had the values of r
where r
is a RasterLayer
(not a brick) then the user should probably have done r1 = r
instead. With its current behaviour the function creates a raster r1
ready to receive new values. Similarly, with a brick:
> r1 = raster(b)
gives the author of the package two choices: either take some data from the brick (but which layer?) or return an empty raster of the same dimension. For consistency with the previous example, the author has chosen to return an empty raster. I'm guessing the author's intentions here, so might be way off, but its certainly a weakness in the documentation that these cases aren't better enumerated. I often find out by trial-and-error with little examples as above.
If you want to convert a brick to a raster, extract whichever layer you want:
r = b[[1]]
for example. So instead of:
> focal(raster(b),fun=mean,w=m)
Error: hasValues(x) is not TRUE
do:
> focal(b[[1]],fun=mean,w=m)
class : RasterLayer
dimensions : 4, 5, 20 (nrow, ncol, ncell)
resolution : 0.2, 0.25 (x, y)
extent : 0, 1, 0, 1 (xmin, xmax, ymin, ymax)
coord. ref. : NA
data source : in memory
names : layer
values : 6, 15 (min, max)
focal
?