Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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:

library(ggmap)
library(rgdal)

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:

plot(city1)

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:

ggmap(map1)+
  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.

library(splancs)
poly1pl <- coordinates(city1) # Extracts long and lat into a matrix
set.seed(2913)
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?

share|improve this question
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. –  Jeffrey Evans Feb 11 '13 at 21:37
add comment

1 Answer 1

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")
  plot(city1)
    points(randpoints,pch=19)
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.