[R-sig-Geo] Replace a polygon by a new one of a SpatialPolygonsDataFrame
Hans-Jörg Bibiko
bibiko at eva.mpg.de
Tue May 12 20:19:14 CEST 2015
Thanks a lot!!!
@Edzer: wrld_simpl at polygons[237] <- theNew
doesn't work. Also due to [<- declaration
@Barry: Yes, removing the old entry and adding the new one via rbind works :) - of course. The clue is to recreate the entire SpatialPolygonsDataFrame. (And sorry for a non-closed polygon ;) )
For the records, I ended up with the following (also in terms of not changing the plot order and the indices):
library(maptools)
data(wrld_simpl)
r <- bbox(wrld_simpl[237,])
theID <- wrld_simpl[237,]@polygons[[1]]@ID
theNew <- list(Polygons(list(
Polygon(cbind(c(r[1,1],r[1,1],r[1,2],r[1,2],r[1,1]),c(r[2,1],r[2,2],r[2,2],r[2,1],r[2,1])))),
theID))
# item which has to be replaced
replace_index <- 237
ws <- wrld_simpl[replace_index,]
wsb <- SpatialPolygonsDataFrame(SpatialPolygons(theNew), data=ws at data)
proj4string(wsb) <- proj4string(wrld_simpl)
wrld_simpl_new <- rbind(wrld_simpl[1:(replace_index-1),], wsb,
wrld_simpl[(replace_index+1):dim(wrld_simpl)[1],])
wrld_simpl_new at plotOrder <- wrld_simpl at plotOrder
plot(wrld_simpl[237, ])
plot(wrld_simpl_new[237,], border="red", add=T)
Again, thanks a lot, you saved my day :)
Best, Hans
More information about the R-sig-Geo
mailing list