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!
The
as
conversion tospatialGridDataFrame
expects an object of classclass SpatialPixelsDataFrame
:So, you can convert your
pts
toSpatialPixelsDataFrame
, then convert the resultingSpatialPixelsDataFrame
toSpatialGridDataFrame
as you did.You can also convert your
rasOut
in the same fashion. In one line of code, this is: