首页 > 解决方案 > R:从长度为 n 的向量中抽取 2 个长度为 n 的随机非重叠样本(对于相同的索引)

问题描述

假设我有一个以all_combinations1 到 20 的数字命名的向量。

我需要提取 2个长度等于 的向量 (coding_1和),在我目前的情况下恰好也是 20。coding_2number_of_peptide_clusters

2 个新向量应从 中随机采样all_combinations,以便在每个索引位置不重叠。

我执行以下操作:

set.seed(3)
all_combinations=1:20
number_of_peptide_clusters=20
coding_1 <- sample(all_combinations, number_of_peptide_clusters, replace = FALSE)
coding_1
 [1]  5 12  7  4 10  8 11 15 17 16 18 13  9 20  2 14 19  1  3  6
coding_2 <- sample(all_combinations, number_of_peptide_clusters, replace = FALSE)
coding_2
 [1]  5  9 19 16 18 12  8  6 15  3 13 14  7  2 11 20 10  4 17  1

这是给我带来麻烦的示例,因为只有一个数字在同一索引处重叠(位置 1 处为 5)。

在这些情况下,我会做的是发现重叠数字并将它们从所有重叠数字列表中重新采样......

想象一下coding_1并且coding_2是:

coding_1
 [1]  5 9  7  4 10  8 11 15 17 16 18 13  12 20 2  14 19  1  3  6
coding_2
 [1]  5 9 19 16 18 12  8  6 15  3 13 14  7  2  11 20 10  4 17  1

在这种情况下,我将在同一位置有 5 和 9 重叠,所以我会coding_2从重叠的完整列表中重新采样它们[重新采样索引 1c(5,9)不等于5,索引 2不等于等于9]。所以coding_2会是:

coding_2
 [1]  9 5 19 16 18 12  8  6 15  3 13 14  7  2  11 20 10  4 17  1

但是,在上述特定情况下,我不能使用这种方法......那么从长度为 20 的向量中获取 2 个长度为 20 的样本的最佳方法是什么,这样样本不会同时重叠索引位置?

如果我能够获得coding_2已经知道的第二个样本,那就太好了coding_1……否则,如果它使事情变得更容易,同时获得 2 个样本也是可以接受的。谢谢!

标签: rreplaceoverlapsample

解决方案


我认为最好的解决方案是简单地使用拒绝策略:

set.seed(3)
all_combinations <- 1:20
number_of_peptide_clusters <- 20
count <- 0
repeat {
  count <- count + 1
  message("Try number ", count)
  coding_1 <- sample(all_combinations, number_of_peptide_clusters, replace = FALSE)
  coding_2 <- sample(all_combinations, number_of_peptide_clusters, replace = FALSE)
  if (!any(coding_1 == coding_2))
    break
}
#> Try number 1
#> Try number 2
#> Try number 3
#> Try number 4
#> Try number 5
#> Try number 6
#> Try number 7
#> Try number 8
#> Try number 9
coding_1
#>  [1] 18 16 17 12 13  8  6 15  3  5 20  9 11  4 19  2 14  7  1 10
coding_2
#>  [1]  5 20 14  2 11  6  7 10 19  8  4  1 15  9 13 17 18 16 12  3

reprex 包于 2020-11-04 创建(v0.3.0)


推荐阅读