[R] Combinations

Romain Francois romain.francois at dbmail.com
Mon Dec 14 11:07:40 CET 2009


On 12/14/2009 10:50 AM, baptiste auguie wrote:
>
> Hi,
>
> Try this,
>
> apply(expand.grid(letters[1:3], letters[24:26]), 1, paste,collapse="")
> [1] "ax" "bx" "cx" "ay" "by" "cy" "az" "bz" "cz"

This will be faster, as it takes advantage of the vectorized paste:

cpaste <- function(...) paste(..., sep = "" )
do.call( cpaste, expand.grid(letters[1:3], letters[24:26]) )

Romain

 > system.time( do.call( cpaste, expand.grid(letters[1:26], 
letters[1:26]) ) )
    user  system elapsed
   0.002   0.000   0.002
 > system.time( apply(expand.grid(letters[1:26], letters[1:26]), 1, 
paste,collapse="") )
    user  system elapsed
   0.015   0.000   0.018

Does not make too much difference on the OP example:

glue <- function( ... ){
   cpaste <- function(...) paste(..., sep = "" )
   do.call( cpaste, do.call( expand.grid, list(...) ) )
}

GLUE <- function(...){
	apply( do.call( expand.grid, list(...) ), 1, paste, collapse = "" )
}


system.time( glue( A = c("a","b","c"), B = c("x", "y", "z"), C = c("l", 
"m", "n"), D = c("p","q","r"), E = c("s", "t", "u") ) )
    user  system elapsed
   0.002   0.000   0.002
 > system.time( GLUE( A = c("a","b","c"), B = c("x", "y", "z"), C = 
c("l", "m", "n"), D = c("p","q","r"), E = c("s", "t", "u") ) )
    user  system elapsed
   0.008   0.000   0.008



> ?expand.grid
>
> HTH,
>
> baptiste
>
> 2009/12/14 Amelia Livington<amelia_livington at yahoo.com>:
>>
>> Dear R helpers,
>>
>> I am working on the scenario analysis pertaining to various interest rates. In this connection I need to form the various combinations as under :
>>
>> Suppose I have two sets A = (a, b, c) and B = (x,y,z)
>>
>> Then I can easily form the cominations as
>> (ax, ay, az, bx, by, bz, cx, cy, cz)
>>
>> However, if I have say 5 variables, then total no of possible combinations will be 3^5 = 243.
>> Thus, A = (a,b,c), B = (x, y, z), C = (l, m, n), D = (p,q,r), E = (s, t, u). Then may be my possble combination will start as (a, x, l, p, s), then next combination may be (a, x, l, p, u) and so on. The last combination (243rd in this case) may be (c, z, n, r, u) or something like this.
>>
>> In R, is there any way to list all these 3^5 = 243 combinations?
>>
>> Amelia



-- 
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr
|- http://tr.im/HlX9 : new package : bibtex
|- http://tr.im/Gq7i : ohloh
`- http://tr.im/FtUu : new package : highlight




More information about the R-help mailing list