Rohit Venkat Gandhi Mendadhala Rohit Venkat Gandhi Mendadhala - 11 months ago 71
R Question

Spatial Polygon sampling error in R

I have a shape file of 200 counties. How should I sample in order to subset counties from the existing 200? I have tried using the below R code:

TXcounties <- readShapePoly("C:/Users/Rvg296/Downloads/TXCountiesShapeFiles/TXCounties.shp")

idx <- sample(1:250, 25, replace = FALSE)
df.TXcounties <-
SpatialPolygonsDataFrame(idx, df.TXcounties).

But this is throwing an error like:

Error in SpatialPolygonsDataFrame(idx, df.TXcounties) : trying to get slot "polygons" from an object of a basic class ("integer") with no slots

Answer Source

The problem is that you are using idx, an integer vector, as the first argument for SpatialPolygonsDataFrame(), but this function needs a spatial polygons object as its first argument. In any case, you should be able to do the whole thing a lot more easily with something like this:

result <- TXcounties[idx,]