I am using R and the package ggmap to try and generate some random points within the city limits of Chapel Hill, NC. I have downloaded the shapefile for the town of Chapel Hill from the Orange County website: http://web.co.orange.nc.us/gisdownloads. The city limits for Chapel Hill and several other nearby cities are in the file labeled city.zip. I saved this file to my hard drive and unzipped it. My code is as follows:


map1 <- get_map(location='Chapel Hill, NC', zoom=12, maptype='roadmap')

setwd('<Path to unzipped city.zip files>')
city <- readOGR('city.shp','city')
sub.city <- city[city$CITYCODE == "CH",] # Take only the part of the shapefile we need (the area around Chapel Hill)
city1 <- spTransform(sub.city, CRS('+proj=longlat +ellps=WGS84'))

If I simply plot city1 the polygon looks as it should:


but if I try to plot it over my street map of Chapel Hill, I get some weird tearing in the northwest part of the city:

  geom_polygon(data=city1, aes(x=long, y=lat), color='blue', fill='blue', alpha=.3)

Why is this and how could I fix it?

The second thing I want to do is generate some random points within this polygon. The package splancs claims to do this with its csr() function, but so far I cannot get this to work.

poly1pl <- coordinates(city1) # Extracts long and lat into a matrix
randpoints <- data.frame(csr(poly1pl, 20)) 

The last command of this gives me an error: Error in runif(ngen) : invalid arguments I get the same error if I try using csr() on sub.city as well, so the error is not a result of using spTransform. What does this error mean and how can I get this to work? Or is there an easier way to generate these points?

  • 1
    The reason for the error is that you cannot extract polygon vertices coordinates using the "coordinate" function. This results in an invalid object being passed to csr. Feb 11 '13 at 21:37

You have two questions here and should consider two separate posts. As to your second question on generating random points. There is no need to use splancs. The rgdal library depends on sp and readOGR results in an sp object. As such, you can use the "spsample" function, without coercion, to generate a set of random points within an sp polygon class object.

randpoints <- spsample(city1, n=20, type="random")

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.