Skip to content
Prev 10961 / 29559 Next

convert a PBSmapping grid to shapefile

On Fri, 18 Feb 2011, Armelle ROUYER wrote:

            
The underlying problem is that makeGrid() understands PolySet objects in 
its own way, with the interaction of PID and SID being a top level 
identifier. In ?PolySet, it looks as though the PID is the top level 
identifier, and SIDs within a given PID are its component parts, not 
independent top-level objects. This is how PolySet2SpatialPolygons() sees 
things too, so the multiple SIDs in a single PID are treated as member 
component polygons of a multipolygon (Polygons) object. So we need to 
disambiguate:

library(PBSmapping)
PS0=makeGrid(x=seq(-5,-1,.2),y=seq(43,49,.2),projection="LL")
PS1 <- as.PolySet(data.frame(PID=as.integer((PS0$PID*100)+PS0$SID),
   SID=1L, POS=PS0$POS, X=PS0$X, Y=PS0$Y), projection="LL")
# Be careful to ensure uniqueness in the new PID!!
PD=read.table("pdata.txt",header=T)
# text file attach
PD1 <- data.frame(PID=as.integer((PD$PID*100)+PD$SID), Z=PD$Z)
# Be careful to ensure uniqueness in the new PID!!
brks=c(fivenum(PD$Z))
cols=c("white","yellow","orange","red","darkred")
PD0=makeProps(PD1,breaks=brks,"col",cols)
plotPolys(PS1, polyProps=as.PolyData(PD0), projection="LL",bg="lightblue")
library(maptools)
sp1 <- PolySet2SpatialPolygons(PS1)
mo <- match(as.character(PD0$PID), row.names(sp1))
Z <- rep(as.numeric(NA), length(row.names(sp1)))
Z[mo] <- PD0$Z
col <- rep(as.character(NA), length(row.names(sp1)))
col[mo] <- PD0$col
df <- data.frame(Z=Z, col=col, stringsAsFactors=FALSE,
   row.names=row.names(sp1))
sp2 <- SpatialPolygonsDataFrame(sp1, data=df)
sp3 <- sp2[!is.na(sp2$Z),]
plot(sp3, col=sp3$col, bg="lightblue", axes=TRUE)
You are right that for this data set, representation as a 
SpatialPixelDataFrame object might be best.

Roger