Reputation: 1756
I have a vector of 50 number in R and I'm generating permutations of this vector using sample()
but my question is:
how much is the total number of combinations that can be generated from this vector without repetition??
and does sample calculates the permutations without repetition ??
what i'm doing is like this:
for (i in 1:100)
{
test$x <- sample(test$x,nrow(test), replace=FALSE)
}
is there any possibilities that i might get repetitive permutations from this code for x column ??
Upvotes: 0
Views: 209
Reputation: 81743
The number of unique permutations of n
values is n!
. If you have, e.g., n = 3
values, the number of permutations is 3 * 2 * 1 = 6
. In R this number can be calculated with factorial(n)
.
Different runs of the function sample
are independent. Hence, it is possible to obtain identical permutations.
If you want to generate all permutations of a set of values, you could use the function permutations
from the gregmisc
package. Here is an example:
# generate a vector of values
dat <- letters[1:3] # [1] "a" "b" "c"
# the number of values to be drawn from the vector
n_samp <- 2 # Note. The maximum number is: length(dat)
library(gregmisc)
# generate the permutations
permutations(length(dat), n_samp, v = dat)
# The result:
[,1] [,2]
[1,] "a" "b"
[2,] "a" "c"
[3,] "b" "a"
[4,] "b" "c"
[5,] "c" "a"
[6,] "c" "b"
Upvotes: 1
Reputation: 18759
As @djurhio mentionned the number of permutations in your example being 50! (i. e. ca. 3e64) is simply too large for you to find all of them. For smaller samples, you can however use function allPerms
from package permute
.
test<-data.frame(x=round(rnorm(5),2)
test
x
1 0.33
2 0.34
3 2.18
4 0.92
5 -0.29
library(permute)
t(apply(allPerms(test$x),1,function(X)test$x[X]))
[,1] [,2] [,3] [,4] [,5]
[1,] 0.33 0.34 2.18 -0.29 0.92
[2,] 0.33 0.34 0.92 2.18 -0.29
...
[118,] -0.29 0.92 2.18 0.33 0.34
[119,] -0.29 0.92 2.18 0.34 0.33
Upvotes: 0
Reputation: 5536
sample(1:3)
.Upvotes: 1