mercredi 10 février 2021

How to take sample() of items that are paired in R and not lose pairs

I have a dataframe of x and y geographic coordinates (30,000+ coordinates) that look like the example matrix points below. I want to take a random sample of these but such that I don't lose the pairs of x and y coordinates.

For example, I know that I can get a random sample of say 2 of the items in x and y, but how do I get a random sample so that items that go together are preserved? In other words, in my matrix of points, one actual point is a pair of an x coordinate (for example, the first item: -12.89) that goes with the first item in the y list: 18.275.

Is there a way that I could put together the items in x and y such that the order is preserved in a tuple-like object (I'm more of a python user) and then take a random sample using sample()? Thanks.

# Make some pretend data
x<-c(-12.89,-15.35,-15.46,-41.17,45.32)
y<-c(18.275,11.370,18.342,18.305,18.301)
points<-cbind(x,y)
points

# Get a random sample:
# This is wrong because the x and y need to be considered together
c(sample(x, 2),
  sample(y, 2))

# This is also wrong because it treats each item in `points` separately
sample(points, size=2, replace=FALSE)

Ultimately, in this example, I would want to end up with two random pairs that go together. For example: (-15.35,11.370) and (45.32,18.301)




Aucun commentaire:

Enregistrer un commentaire