I have a polygon shapefile with 2 features. I want to split the MultiPolygon shp into separate shapefiles based on a column of the attribute table. What I've tried so far is this code based on that answer but without success:
all_shp = readOGR("mydir", layer = "test")
#extract features to a new polygon
shp1 = all_shp[1,]
writeOGR(shp1, dsn = "mydir", layer = "shp1",
driver = "ESRI Shapefile" )
#create function
extract_shp = function(all_shp){
#iterate through the feature class
for(i in 1:nrow(all_shp)) { p <- all_shp[i,] }
#extract features to a new polygon
shp1 = p
}
I am pasting the data using the dput
command:
test = new(
"SpatialPolygonsDataFrame",
data = structure(
list(
id = c(14985,
23552),
left = c(2665569.79702, 2670699.79702),
top = c(1412205.45671,
1407615.45671),
right = c(2665839.79702, 2670969.79702),
bottom = c(1411935.45671,
1407345.45671),
id_sample = c(1L, 1L)
),
class = "data.frame",
row.names = 0:1
),
polygons = list(
new(
"Polygons",
Polygons = list(
new(
"Polygon",
labpt = c(80.3367355387047, 16.2821390031233),
area = 6.1440311016086e-06,
hole = FALSE,
ringDir = 1L,
coords = structure(
c(
80.3354759967946,
80.3379981575006,
80.3379950690668,
80.3354729314431,
80.3354759967946,
16.2833585003835,
16.2833555285503,
16.2809195021546,
16.2809224739735,
16.2833585003835
),
.Dim = c(5L,
2L)
)
)
),
plotOrder = 1L,
labpt = c(80.3367355387047, 16.2821390031233),
ID = "0",
area = 6.1440311016086e-06
),
new(
"Polygons",
Polygons = list(
new(
"Polygon",
labpt = c(80.3523654989901,
16.2402853833502),
area = 6.1434245505222e-06,
hole = FALSE,
ringDir = 1L,
coords = structure(
c(
80.3511062267076,
80.3536279907441,
80.353624759728,
80.3511030187666,
80.3511062267076,
16.2415050209594,
16.2415019107378,
16.2390657420334,
16.2390688522397,
16.2415050209594
),
.Dim = c(5L, 2L)
)
)
),
plotOrder = 1L,
labpt = c(80.3523654989901,
16.2402853833502),
ID = "1",
area = 6.1434245505222e-06
)
),
plotOrder = 1:2,
bbox = structure(
c(
80.3354729314431,
16.2390657420334,
80.3536279907441,
16.2833585003835
),
.Dim = c(2L, 2L),
.Dimnames = list(c("x", "y"), c("min", "max"))
),
proj4string = new("CRS",
projargs = "+proj=longlat +datum=WGS84 +no_defs")
)
I am using RStudio 1.4.1717, R 4.1.1 and Windows10 x64