Turn SpatialPointsDataframe to SpatialGridDataframe

1.1k views Asked by At

I am trying to convert a SpatialPointsDataframe to a SpatialGridDataframe in order to use the slopeasp() function from the landsat package to get the values for slope. I tried to convert the SpatialPointsDataframe to a raster to convert it but it also didn't work and I get the error.

Error in as(pts, "spatialGridDataFrame") : no method or default for coercing “SpatialPointsDataFrame” to “spatialGridDataFrame”

Here is my code below:

#create fake data
x <- rep(rep(seq(12,36,0.5),41))
y <-rep(seq(32,52,0.5), each=49)
z <- rnorm(2009, 26.5, 44.0)
pts <- as.data.frame(matrix(c(x,y,z),  ncol=3,  byrow=FALSE))
colnames(pts)=c("x", "y", "z")

# create a SpatialPointsDataFrame
coordinates(pts) = ~x+y                                        
# create an empty raster object to the extent of the points
rast <- raster(ext=extent(pts), resolution=250)
# rasterize  irregular points 
rasOut<-rasterize(pts, rast, pts$z, fun = mean)

#attempt from spdf to sgdf
sgdf <- as(pts, 'spatialGridDataFrame')
#atempt from raster to sgdf
sgdf <- as(rasOut, 'spatialGridDataFrame')

Does anyone have any suggestions on how to get a spatialGridDataFrame? Thanks!

1

There are 1 answers

1
Liman On BEST ANSWER

The as conversion to spatialGridDataFrame expects an object of class class SpatialPixelsDataFrame:

Objects from the Class

Objects can be created by calls of the form as(x, "SpatialGridDataFrame"), where x is of class SpatialPixelsDataFrame-class, or by importing through rgdal. Ordered full grids are stored instead or unordered non-NA cells;

So, you can convert your pts to SpatialPixelsDataFrame, then convert the resulting SpatialPixelsDataFrame to SpatialGridDataFrame as you did.

#attempt from spdf to sgdf
sgdf <- as(pts, 'SpatialPixelsDataFrame')

# Convert the SpatialPixelsDataFrame (sgdf) to spatialGridDataFrame
sgdf <- as(sgdf, "SpatialGridDataFrame")

You can also convert your rasOut in the same fashion. In one line of code, this is:

#atempt from raster to sgdf
sgdf <- as(as(rasOut, 'SpatialPixelsDataFrame'), 'SpatialGridDataFrame')