Removing the third dimension in SpatialPointsDataFrame

2.1k views Asked by At

I have a SpatialPoints object with 3 dimensions :

x <- c(1,1,1,2,2,2,3,3,3)
y <- c(1,2,3,1,2,3,1,2,3)
z <- c(1,3,5,2,1,2,1,2,3)
xyz <- cbind(x,y,z)
ss <- SpatialPoints(xyz)
dimensions(ss)

And a raster object:

rr <- raster(matrix(round(runif(49,0,10)),7,7), xmn=0, xmx=4, ymn=0, ymx=4, crs=NA, template=NULL)

I want to extract the raster values using the SpatialPoints object:

 extract(rr,ss)
#Error in .xyValues(x, coordinates(y), ..., df = df) : 
#  xy should have 2 columns only.
#Found these dimensions: 9, 3

You can visualize the data if you want:

plot(rr)
plot(ss, add=T)

So the problem is that the extract function of the raster package require a 2 dimension SpatialPoints object. Mine (in my real data) in 3 dimensional. Is there a way to drop the 3rd dimension of my point shape? I've tried:

coordinates(ss) <- coordinates(ss)[,-3]
#Error in `coordinates<-`(`*tmp*`, value = c(1, 1, 1, 2, 2, 2, 3, 3, 3,  : 
#  setting coordinates cannot be done on Spatial objects, where they have #already been set

I don't want to have to rebuild my shape from scratch.

2

There are 2 answers

1
rcs On BEST ANSWER

Just overwrite the coords slot of the S4 object:

ss@coords <- ss@coords[, 1:2]

I don't know how your SpatialPoints object is created, but if you use rgdal::readOGR there is a pointDropZ argument (default FALSE)

0
Bastien On

@rcs answer is better, but this works as well:

ss <- SpatialPoints(coordinates(ss)[,-3])   

and if you have a SpatialPointsDataFrame:

ss <- SpatialPointsDataFrame(coordinates(ss)[,-3], ss@data,proj4string=CRS(proj4string(ss)))