From @oko| @end|ng |rom |n@@-tou|ou@e@|r  Fri Jan 13 11:11:44 2023
From: @oko| @end|ng |rom |n@@-tou|ou@e@|r (Serguei Sokol)
Date: Fri, 13 Jan 2023 11:11:44 +0100
Subject: [Rd] Combinations and Permutations
In-Reply-To: <SY2PR01MB300330598A24A015C383C89CCDEB9@SY2PR01MB3003.ausprd01.prod.outlook.com>
References: <SY2PR01MB300330598A24A015C383C89CCDEB9@SY2PR01MB3003.ausprd01.prod.outlook.com>
Message-ID: <e7ce1401-434d-90a4-f7ca-ff995dce3bdc@insa-toulouse.fr>

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 at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel



[Rd] Combinations and Permutations
Serguei Sokol