【问题标题】:How to take sample() of items that are paired in R and not lose pairs如何获取在 R 中配对且不丢失对的项目的 sample()
【发布时间】:2021-05-14 12:31:18
【问题描述】:

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

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

有没有一种方法可以将 xy 中的项目放在一起,以便将顺序保存在一个类似元组的对象中(我更像是一个 python 用户),然后随机抽样使用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)

【问题讨论】:

  • 只需采样索引号idx &lt;- sample(1:length(x), size=1) 并使用它,例如x[idx]y[idx]

标签: r matrix random tuples sample


【解决方案1】:

另一种选择可能是:

set.seed(123)
do.call(`rbind`, sample(asplit(points, 1), 2))

          x      y
[1,] -15.35 11.370
[2,] -41.17 18.305

【讨论】:

  • 你能解释一下为什么你使用set.seed(123)而Markus使用set.seed(42)吗?
  • 就是为了在重复运行时得到同样的结果。可以使用任何数字。见stackoverflow.com/questions/13605271/…
【解决方案2】:

您可以从行索引中获取sample

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

给予

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

【讨论】:

  • 谢谢。为什么包含set.seed()
  • set.seed() 只是确保伪随机性是可重复的。见,例如this link。或者,运行此代码并仔细查看输出:set.seed(1); rnorm(5); rnorm(5); set.seed(1); rnorm(5)
  • 所以要明确@JAG2024,不要在你自己的代码中使用 set.seed() ,它就在那里,所以在运行这段代码时都会得到上面打印的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-02
  • 1970-01-01
  • 2020-02-09
  • 2018-02-07
  • 1970-01-01
  • 1970-01-01
  • 2014-07-18
相关资源
最近更新 更多