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

JAG*_*024 1 random tuples r sample matrix

我有一个 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)
Run Code Online (Sandbox Code Playgroud)

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

mar*_*kus 5

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

set.seed(42)
points[sample(seq_len(nrow(points)), 2), ]
Run Code Online (Sandbox Code Playgroud)

#          x      y
#[1,] -12.89 18.275
#[2,]  45.32 18.301
Run Code Online (Sandbox Code Playgroud)

  • `set.seed()` 只是确保伪随机性是可重复的。请参阅,例如[此链接](http://rfunction.com/archives/62)。或者,运行此代码并仔细查看输出:`set.seed(1); 范数(5); 范数(5); 设置.seed(1); rnorm(5)`。 (3认同)