-1

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:

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

idx <- sample(1:250, 25, replace = FALSE)
df.TXcounties <- as.data.frame(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

Phil
  • 4,344
  • 2
  • 23
  • 33
  • Please can you provide a [minimal reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)? Instead of using `maptools::readShapePoly()` I suggest `rgdal::readOGR()` because it reads the projection in. – Phil Nov 05 '16 at 11:05

1 Answers1

0

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,]
John R.B. Palmer
  • 2,082
  • 3
  • 17
  • 23