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?