'checking if two sets are equal where order doesn't matter in R?
so I am trying to write a simulation to test the probability of a certain topping selection coming up when picking 4 toppings on a pizza. (total topping selection = 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)
I have the exact probability done on paper, and the above attempt is the closest i can get to it, without the sorting its worse, which tells me that this is making order matter. is there any built in functions in R that will check if 2 sets are equal where order doesn't matter?
Solution 1:[1]
Use replicate to run the simulations. From the documentation of ?replicate, my emphasis:
replicateis a wrapper for the common use of sapply for repeated evaluation of an expression (which will usually involve random number generation).
In the code below I set the pseudo-RNG seed in order to make the results reproducible.
# 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
Created on 2022-03-08 by the reprex package (v2.0.1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rui Barradas |
