Can a raster
object (in R) have layers of different mode (data type)?
On the face of it it seems we are always forced to one type:
library(raster)
## create a SpatialPixelsDataFrame with (trivially) two different "layer" types
d <- data.frame(expand.grid(x = 1:10, y = 2:11), z = 1:100, a = sample(letters, 100, replace = TRUE), stringsAsFactors = FALSE)
coordinates(d) <- 1:2
gridded(d) <- TRUE
## now coerce this to a raster brick or stack and our "a" is crushed to numeric NA
all(is.na(getValues(brick(d)[[2]])))
[1] TRUE
Is there anything like a rasterDataFrame?
Also, note that we presumably cannot use R's factors since the raster@data is a matrix, or otherwise coerced to numeric/integer. Am I missing something?
The raster
package provides the ability to create rasters with a categorical variable, and the rasterVis
package includes functions for plotting them. The ratify
function allows a raster to include a lookup table relating the underlying raster integer values to other values, which can be character. This directly allows the use of any other mode of value in the levels part of the ratified raster.
Here's an example.
library(rasterVis)
r <- raster(xmn = 0, xmx = 1, ymn = 0, ymx = 2, nrow = 10, ncol = 11,
crs = as.character(NA))
r[] <- sample(seq_along(letters[1:5]), ncell(r), replace = TRUE)
## ratify the raster, and set up the lookup table
r <- ratify(r)
rat <- levels(r)[[1]]
rat$value <- letters[1:5]
rat$code <- 1:5
## workaround for limitation as at 2013-05-01
## see https://stat.ethz.ch/pipermail/r-sig-geo/2013-May/018180.html
rat$code <- NULL
levels(r) <- rat
levelplot(r)
There are coming updates to rasterVis
that make the workaround above unnecessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With