如何在R中配对并且不丢失对的项目的样本()

我有一个 x 和 y 地理坐标(30,000+ 个坐标)的数据框,看起来像points下面的示例矩阵。我想随机抽取这些样本,但这样我就不会丢失 x 和 y 坐标对。

例如,我知道我可以在xand 中获得 2 个项目y的随机样本,但是如何获得随机样本以便保留在一起的项目?换句话说,在我的矩阵 中points,一个实际点是一对 x 坐标(例如,第一项:-12.89),它与y列表中的第一项:18.275 一致。

有没有一种方法,我可以放在一起的项目中x,并y使得订单一座保存完好的元组类对象(我更蟒用户),然后采取使用随机样本sample()?谢谢。

# 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)

最终,在这个例子中,我希望最终得到两个随机配对。例如:(-15.35,11.370) 和 (45.32,18.301)

回答

您可以sample从行索引中获取 a :

set.seed(42)
points[sample(seq_len(nrow(points)), 2), ]

#          x      y
#[1,] -12.89 18.275
#[2,]  45.32 18.301

  • `set.seed()` just ensures that psuedo-randomness is repeatable. See, e.g. [this link](http://rfunction.com/archives/62). Alternatively, run this code and look carefully at the output: `set.seed(1); rnorm(5); rnorm(5); set.seed(1); rnorm(5)`.

以上是如何在R中配对并且不丢失对的项目的样本()的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>