@Frank -- That's an interesting idea, but I worry that it's too dependent on which point you choose as the first point. In other words, for the same vector, different starting points would give different results (although the same is true for the algorithm in general). Probably the right way to do something like that is calculate a distance matrix for all points and then do a bit of graph theory to group the points by mutual distance. Give it a try :)
This is a great function you've made here! But I was wondering if it is possible to find multiple closed contours in one X and Y vector?
maybe using an if statement when the starting point is closer than any other data point it closes the contour and starts a new one on the next point of your vector?
I think this would be a very nice addition to your program for when your working with big spatial datasets.