5

I have a regular data.frame called datos.merged

class(datosmerged)

[1] "data.frame"

The last two columns are the corresponding geographical coordinates

datosmerged[1,c(23,24)]

   XCOORD   YCOORD
1 2473520   668648.7

I have a file called shape

class(shape)

[1] "SpatialPolygonsDataFrame"
attr(,"package")
[1] "sp"

I would like to use this very simple shape to subset the previous data.frame. How can this be done?

8

You can easily coerce your data.frame to an sp SpatialPointsDataFrame object.

coordinates(datosmerged) <- ~XCOORD+YCOORD
  class(datosmerged)

Assuming that "shape" is a polygon, you can then use the "over" function to identify overlap between the two feature classes. An alternative is "gIntersects" in the "rgeos" package but it a bit overkill for you problem.

Here is an example

require(sp)

# Create polygons
r1 = cbind(c(180114, 180553, 181127, 181477, 181294, 181007, 180409, 
  180162, 180114), c(332349, 332057, 332342, 333250, 333558, 333676, 
  332618, 332413, 332349))
r2 = cbind(c(180042, 180545, 180553, 180314, 179955, 179142, 179437, 
  179524, 179979, 180042), c(332373, 332026, 331426, 330889, 330683, 
  331133, 331623, 332152, 332357, 332373))
srdf=SpatialPolygonsDataFrame(SpatialPolygons(list(Polygons(list(Polygon(r1)),"r1"),
                              Polygons(list(Polygon(r2)),"r2"))), data.frame(ID=c(1,2), 
                              row.names=c("r1","r2")))

# Coerce data.frame to SpatialPointsDataFrame
data(meuse)
  coordinates(meuse) = ~x+y

# Plot Example  
plot(meuse, pch=19)
  plot(srdf, add=T)

# Use over function to add polygon IDS to points. Non-overlapping points will have NA 
meuse@data <- data.frame(meuse@data, over(meuse, srdf[,"ID"]) )
  meuse@data

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.