This is how I plot multiple raster
library(raster)
x <- raster::getData('worldclim', var='tmin', res = 10)
var.list <- c("tmin1","tmin2","tmin3","tmin4")
ras.stack <- stack()
for(i in var.list){
stack.list <- stack(stack.list, x[[paste0(i)]])
}
spplot(stack.list)
I want to do the same for 4 shape files which have a common attribute called "mean.value"
fra <- raster::getData('GADM',country = 'FRA', level = 2)
shp.stack <- stack()
for(i in 1:4){
mean.value <- data.frame(NAME_2 = fra@data$NAME_2, sample(1:200, 96))
my.shp <- merge(fra, mean.value, by = 'NAME_2')
shp.stack <- stack(shp.stack, my.shp)
}
Error in sapply(x, fromDisk) & sapply(x, inMemory) : operations are possible only for numeric, logical or complex types
How can I fix it?
You have to transform the SpatialPolygonsDataFrame
to a raster object first, to be able to stack it. You could also transform to SpatialGrid*, SpatialPixels* - objects based on the manual of raster::stack
.
So your second code would become something like this:
library(raster)
fra <- raster::getData('GADM',country = 'FRA', level = 2)
shp.stack <- stack()
for(i in 1:4){
mean.value <- data.frame(NAME_2 = fra@data$NAME_2, sample(1:200, 96))
my.shp <- raster::merge(fra, mean.value, by = 'NAME_2')
r <- raster(ncol=180, nrow=180)
extent(r) <- extent(my.shp)
rp <- rasterize(x = my.shp, y = r)
shp.stack <- raster::stack(shp.stack, rp)
}
plot(shp.stack)