Ladislav Naďo
Ladislav Naďo

Reputation: 862

How to make MCP polygon from points in R

I have a problem when trying to make MCP from many points in R.

library(shapefiles)

# no problem when only three points...
dd <- data.frame(Id=c(1,1,1,1),X=c(3,5,8,3),Y=c(9,8,3,9))
ddTable <- data.frame(Id=c(1),Name=c("Item1"))
ddShapefile <- convert.to.shapefile(dd, ddTable, "Id", 5)
write.shapefile(ddShapefile, "/directory.../pgn_test", arcgis=T)
my.pgn <- readOGR("/directory...","pgn_test")
plot(my.pgn)
points(dd$X, dd$Y, cex = 0.7, pch = 1)

Code above works perfectly when only three points are given, however in my case there are many points...

# when some points are inside the polygon
dd <- data.frame(Id=c(rep(1, times = 6)),X=c(1,2,3,5,5,1),Y=c(1,5,3,5,1,1))
ddTable <- data.frame(Id=c(1),Name=c("Item1"))
ddShapefile <- convert.to.shapefile(dd, ddTable, "Id", 5)
write.shapefile(ddShapefile, "/directory.../pgn_test", arcgis=T)
my.pgn <- readOGR("/directory...","pgn_test")
plot(my.pgn)
points(dd$X, dd$Y, cex = 0.7, pch = 1)

enter image description here

Can anybody know how to solve this situation?

Upvotes: 2

Views: 772

Answers (1)

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162431

You could just use the base R function chull(), which "computes the subset of points which lie on the convex hull of the set of points specified":

dd <- data.frame(X = c(1,2,3,5,5,1), Y = c(1,5,3,5,1,1))

ii <- with(dd, chull(X,Y))
ii <- c(ii, ii[1])

plot(Y~X, data=dd)
lines(Y~X, data=dd[ii,])

enter image description here

Upvotes: 5

Related Questions