r - R:从长度为 n 的向量中抽取 2 个长度为 n 的随机非重叠样本(对于相同的索引)
问题描述
假设我有一个以all_combinations
1 到 20 的数字命名的向量。
我需要提取 2个长度等于 的向量 (coding_1
和),在我目前的情况下恰好也是 20。coding_2
number_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 个样本也是可以接受的。谢谢!
解决方案
我认为最好的解决方案是简单地使用拒绝策略:
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)
推荐阅读
- swift - 如何在 macOS 上使 SwiftUI 的 Picker 无边框/透明?
- python - ValueError: int() 以 10 为基数的无效文字:'81?36N'
- amazon-web-services - 如何显示托管在 S3 中的静态网站的先前版本
- r - 如何对数据框的每一行应用函数?
- python - 如何仅操作字符串中单词的中心值(不是第一个和最后一个)?
- python - 在 minimum_squares 中调用函数作为参数返回“TypeError:'numpy.ndarray'对象不可调用”
- python - 如何使用 Pandas 和 Python 创建新变量并将其添加到数据框以打印到 excel?
- python - python/tkinter 弹出窗口在 windows 或 linux 上显示正常,但在 OSX Mojave 上不显示。没有错误
- c - C:初始化结构并将其分配给函数参数中的指针
- latex - 左对齐显示居中的脚注