5

How to produce "SpatialPixelsDataFrame" from staccked RasterLayer ?

I have a stacked rasterlayer and I want to convert them to SpatialPixelsDataFrame.

RasterLayer information is

> RAD.all[[1]]
class       : RasterLayer 
dimensions  : 180, 240, 43200  (nrow, ncol, ncell)
resolution  : 0.01, 0.01  (x, y)
extent      : -123.305, -120.905, 36.705, 38.505  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0 
data source : C:\Users\Michael\Documents\1998bil\1998ASC5min_ppt_spas1214_0001_19980202_0810_UTC.asc.bil 
names       : X1998ASC5min_ppt_spas1214_0001_19980202_0810_UTC.asc 
2

There are two nice packages in (Macro)Ecology that have a workaround for what you want to do:

library(raster)
library(SDMTools)
library(adehabitat)

r <- raster("yourFile.tif") # Get a link to a raster
rAsc <- asc.from.raster(r) # Function from SDMTools to convert to asc format
b <- asc2spixdf(rAsc) # Function from adehabitat to convert to SpatialPixelDataFrame
class(b) # See if it worked
>[1] "SpatialPixelsDataFrame"
>attr(,"package")
>[1] "sp"

Then just apply this in a loop or via StackApply and a custom function to your stacked object.

  • Thanks a lot. It worked. Yes, I can see > class(b) [1] "SpatialPixelsDataFrame" attr(,"package") [1] "sp" > – Nahm Aug 23 '14 at 8:47
  • Very inefficient approach. mdsummer's suggestion is the correct answer. – Robert Hijmans Sep 3 '14 at 17:32
11

Coercion methods are included in the raster package:

as(RAD.all, "SpatialPixelsDataFrame")
  • It works very well. Thanks. > AA <- as(RAD.all, "SpatialPixelsDataFrame") > class(AA) [1] "SpatialPixelsDataFrame" attr(,"package") [1] "sp" – Nahm Aug 24 '14 at 1:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.