检查两个集合是否相等,而 R 中的顺序无关紧要?



所以我试图写一个模拟来测试在披萨上挑选4种浇头时出现特定浇头选择的概率。(总浇头选择=7(

toppings = sample(c(1,2,3,4,5,6,7),4,replace = FALSE)
certainSelection = c(1,2,3,4)
toppingsSorted = sort(toppings)
certainSelectionCounter = ifelse(certainSelection == toppingsSorted, certainSelectionCounter + 1, certainSelectionCounter)

我在纸上做了确切的概率,上面的尝试是我能得到的最接近的,而没有排序更糟,这告诉我,这让秩序很重要。R中是否有任何内置函数可以检查两个集合是否相等,而顺序无关紧要?

使用replicate运行模拟。从?replicate的文档来看,我的重点是:

replicate是一个包装器,用于常见的sapply对表达式的重复求值(通常涉及随机数生成(。

在下面的代码中,我设置了伪RNG种子,以便使结果可重复。

# compare the draws with this vector
certainSelection <- c(1,2,3,4)
# number of simulations, 10K
R <- 1e5
set.seed(2022)
res <- replicate(R, {
toppings <- sample(c(1,2,3,4,5,6,7),4,replace = FALSE)
setequal(certainSelection, toppings)
})
mean(res)
#> [1] 0.0286
1/choose(7, 4)
#> [1] 0.02857143

创建于2022-03-08由reprex包(v2.0.1(

最新更新