[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 19:07:17 CEST 2015


Dear all,

I believe I do not see the forest for the trees. Since hours I've been trying something very basal. Maybe someone could give me an hint.

Imaging the following scenario:

I have a SpatialPolygonsDataFrame which contains lots of spatial polygons and associated data. Now I'd like to replace one polygon (a list of a Polygons-class) of that SpatialPolygonsDataFrame by a new one. How can I do this.


Here is a very naïve, reproducible example:

Task: Replace the Polygons showing "Western Sahara" of the data set "world_simpl" by a new one which only shows its rectangle (bbox).

---------------------------------------------------------------
library(maptools)
data(wrld_simpl)

#wrld_simpl[237,] := Western Sahara
r <- bbox(wrld_simpl[237,])

theID <- wrld_simpl[237,]@polygons[[1]]@ID

# create the new spatial polygon (a rectangle of bbox coordinates) 
theNew <- list(Polygons(list(Polygon(cbind(c(r[1,1],r[1,1],r[1,2],r[1,2]),c(r[2,1],r[2,2],r[2,2],r[2,1])))), theID))

# now I thought that one can do the this:
wrld_simpl[237,]@polygons <- theNew

---------------------------------------------------------------

But the last line does't work albeit the class and list resp. are of the same structure. :/

Old:
> str(wrld_simpl[237,]@polygons)
List of 1
 $ :Formal class 'Polygons' [package "sp"] with 5 slots
  .. ..@ Polygons :List of 1
  .. .. ..$ :Formal class 'Polygon' [package "sp"] with 5 slots
  .. .. .. .. ..@ labpt  : num [1:2] -13.1 24.7
  .. .. .. .. ..@ area   : num 24
  .. .. .. .. ..@ hole   : logi FALSE
  .. .. .. .. ..@ ringDir: int 1
  .. .. .. .. ..@ coords : num [1:23, 1:2] -15.7 -17 -17.1 -16.9 -16.7 ...
  .. ..@ plotOrder: int 1
  .. ..@ labpt    : num [1:2] -13.1 24.7
  .. ..@ ID       : chr "ESH"
  .. ..@ area     : num 24


New:
> str(theNew)
List of 1
 $ :Formal class 'Polygons' [package "sp"] with 5 slots
  .. ..@ Polygons :List of 1
  .. .. ..$ :Formal class 'Polygon' [package "sp"] with 5 slots
  .. .. .. .. ..@ labpt  : num [1:2] -14.3 10.5
  .. .. .. .. ..@ area   : num 159
  .. .. .. .. ..@ hole   : logi FALSE
  .. .. .. .. ..@ ringDir: int 1
  .. .. .. .. ..@ coords : num [1:5, 1:2] -17.05 -17.05 -8.67 -8.67 -17.05 ...
  .. ..@ plotOrder: int 1
  .. ..@ labpt    : num [1:2] -14.3 10.5
  .. ..@ ID       : chr "ESH"
  .. ..@ area     : num 159

?

I really appreciate any help someone can provide!

Cheers, Hans



More information about the R-sig-Geo mailing list