I have a SpatialPixelDataFrame (spdf) which contains gridded values (UD) for different Unique id's (n = 21).
I would like to create an individual raster for each Unique_id, with value (UD) as the cell value.
I can create a single raster using the following:
single.ras <- raster(spdf)
Is there a way to group the data by Unique_id and produce multiple raster files (e.g. in the form of a Raster stack?)
For example, for an estUDm object, I have the following code which creates a stack of rasters, one for each Unique id. However, the difference here is that the individual Unique_id "objects" are already inherent in the estUDm object.
multi.ras <- stack(lapply(estUDm.data, raster))
I have tried to adapt a code that uses a loop, but this just produces the same raster 16 (? why 16?) times. So something is not correct (I know next to nothing about loops).
## Loop
datagroup <- unique(df.sp$Unique_id)
result <- list()
for (i in 1:length(datagroup)) {
result[[i]] <- raster(df.sp)
}
s <- stack(result)
plot(s)
The data structure of my spdf is as follows; apologies I do not know how to recreate such data.
> str(spdf)
Formal class 'SpatialPixelsDataFrame' [package "sp"] with 7 slots
..@ data : tibble [623 x 2] (S3: tbl_df/tbl/data.frame)
.. ..$ UD : num [1:623] 0.1064 0.0997 0.0937 0.0346 0.0414 ...
.. ..$ Unique_id: chr [1:623] "Fixed gear_2013_B" "Fixed gear_2013_B" "Fixed gear_2013_B" "Fixed gear_2013_B" ...
..@ coords.nrs : num(0)
..@ grid :Formal class 'GridTopology' [package "sp"] with 3 slots
.. .. ..@ cellcentre.offset: Named num [1:2] -69.2 -55.8
.. .. .. ..- attr(*, "names")= chr [1:2] "Lon" "Lat"
.. .. ..@ cellsize : Named num [1:2] 0.5 0.5
.. .. .. ..- attr(*, "names")= chr [1:2] "Lon" "Lat"
.. .. ..@ cells.dim : Named int [1:2] 27 14
.. .. .. ..- attr(*, "names")= chr [1:2] "Lon" "Lat"
..@ grid.index : int [1:623] 247 220 166 139 112 85 248 248 221 194 ...
..@ coords : num [1:623, 1:2] -67.8 -67.8 -67.8 -67.8 -67.8 ...
.. ..- attr(*, "dimnames")=List of 2
.. .. ..$ : chr [1:623] "1" "2" "3" "4" ...
.. .. ..$ : chr [1:2] "Lon" "Lat"
..@ bbox : num [1:2, 1:2] -69.5 -56 -56 -49
.. ..- attr(*, "dimnames")=List of 2
.. .. ..$ : chr [1:2] "Lon" "Lat"
.. .. ..$ : chr [1:2] "min" "max"
..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot
.. .. ..@ projargs: chr "+proj=longlat +datum=WGS84 +no_defs"