[Rd] Combinations and Permutations
Serguei Sokol
@oko| @end|ng |rom |n@@-tou|ou@e@|r
Fri Jan 13 11:11:44 CET 2023
Le 13/01/2023 à 09:00, Dario Strbenac via R-devel a écrit :
> Good day,
>
> In utils, there is a function named combn. It would seem complementary for utils to also offer permutations because of how closely mathematically related they are to each other. Could permutations be added to save on a package dependency if developing a package?
If you need a function returning a matrix with all permutations of a
vector x in its columns, a simple recursive one-liner can be sufficient,
no need for a whole package dependency for this:
perm=function(x) {n=length(x); f=factorial(n); if (n>1)
structure(vapply(seq_along(x), function(i) rbind(x[i], perm(x[-i])),
x[rep(1L, f)]), dim=c(n, f)) else x}
It works for all king of vectors (integer, numeric, character, ...):
perm(1:3)
perm(pi*1:3)
perm(letters[1:3])
Obviously, a particular attention should be brought to the size of x
(referred here as n) as the column number in the returned matrix growths
as n!.. E.g. 8!=40320. So growths the cpu time too.
Hoping it helps,
Serguei.
>
> --------------------------------------
> Dario Strbenac
> University of Sydney
> Camperdown NSW 2050
> Australia
> ______________________________________________
> R-devel using r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
More information about the R-devel
mailing list