1

I want to create a SpatialPointDataFrame and Voronoi Tesselation from my .csv data downloaded from EPA, available here: http://uloz.to/xboQc7cu/no2-calif-csv

I convert my data in SPDF format in 2 ways:

my.tab<-read.csv("no2_calif.csv", stringsAsFactors = FALSE, sep = "")
coordinates(my.tab) <- ~ Longitude + Latitude 

or

my.tab<-read.csv("no2_calif.csv", stringsAsFactors = FALSE, sep = "")
my.tab.spdf<- SpatialPointsDataFrame(cbind(my.tab$Longitude, my.tab$Latitude), my.tab)

and use Voronoi tesselation published here: http://carsonfarmer.com/2009/09/voronoi-polygons-with-r/

voronoipolygons = function(layer) {
    require(deldir)
    crds = layer@coords
    z = deldir(crds[,1], crds[,2])
    w = tile.list(z)
    polys = vector(mode='list', length=length(w))
    require(sp)
    for (i in seq(along=polys)) {
        pcrds = cbind(w[[i]]$x, w[[i]]$y)
        pcrds = rbind(pcrds, pcrds[1,])
        polys[[i]] = Polygons(list(Polygon(pcrds)), ID=as.character(i))
    }
    SP = SpatialPolygons(polys)
    voronoi = SpatialPolygonsDataFrame(SP, data=data.frame(x=crds[,1], 
        y=crds[,2], row.names=sapply(slot(SP, 'polygons'), 
        function(x) slot(x, 'ID'))))
}

Using either

my.tab.voro <-voronoipolygons(my.tab)

or

my.tab.spdf.voro <-voronoipolygons(my.tab.spdf)

I obtain back the error:

 Error in data.frame(x = crds[, 1], y = crds[, 2], row.names = sapply(slot(SP,  : 
  row names supplied are of the wrong length 

Please, where the problem could be? do I need to have my coordinates in XY format? if yes, please, how? just reproject my data?

  • just give it dummy data voronoi = SpatialPolygonsDataFrame(SP, data=data.frame(x = seq(length(SP)))) or do return(SP) and work with that instead - it's got nothing to do with the coordinate system. If you make a reproducible example someone might fix it. – mdsumner Apr 25 '16 at 5:40
  • thank you @mdsumner but it doesn't work... – maycca Apr 25 '16 at 5:46
3

Reproducible example, just fix the script to make a dummy data.frame.

voronoipolygons = function(layer) {
require(deldir)
crds = layer@coords
z = deldir(crds[,1], crds[,2])
w = tile.list(z)
polys = vector(mode='list', length=length(w))
require(sp)
for (i in seq(along=polys)) {
    pcrds = cbind(w[[i]]$x, w[[i]]$y)
    pcrds = rbind(pcrds, pcrds[1,])
    polys[[i]] = Polygons(list(Polygon(pcrds)), ID=as.character(i))
}
SP = SpatialPolygons(polys)
 voronoi = SpatialPolygonsDataFrame(SP, data=data.frame(dummy = seq(length(SP)), row.names=sapply(slot(SP, 'polygons'), 
    function(x) slot(x, 'ID'))))
}

library(sp)
data(meuse)
coordinates(meuse) <- c("x", "y")

vp <- voronoipolygons(meuse)

plot(vp)

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.