[R] generate combination set
Bill.Venables at csiro.au
Bill.Venables at csiro.au
Thu Nov 15 21:29:44 CET 2007
Actually, (now that I know about combn), a better way is
t(matrix(set[combn(7,2)], nrow = 2))
Bill V.
-----Original Message-----
From: Adrian Dusa [mailto:dusa.adrian at gmail.com]
Sent: Thursday, 15 November 2007 11:55 PM
To: Venables, Bill (CMIS, Cleveland)
Cc: aiminy at iastate.edu; r-help at r-project.org
Subject: Re: [R] generate combination set
Using your "set", wouldn't it be simpler like this?
t(apply(combn(7,2), 2, function(x) set[x]))
Hth,
Adrian
On Thursday 15 November 2007, Bill.Venables at csiro.au wrote:
> There are a number of packages that do this, but here is a simple
> function for choosing subsets:
>
> subsets <- function(n, r) {
> if(is.numeric(n) & length(n) == 1) v <- 1:n else {
> v <- n
> n <- length(v)
> }
> subs <- function(n, r, v)
> if(r <= 0) NULL else
> if(r >= n) matrix(v[1:n], nrow = 1) else
> rbind(cbind(v[1], subs(n - 1, r - 1, v[-1])),
> subs(n - 1, r , v[-1]))
> subs(n, r, v)
> }
>
> Here is an example of how to use it:
> > set <- LETTERS[1:7]
> > subsets(set, 2)
>
> [,1] [,2]
> [1,] "A" "B"
> [2,] "A" "C"
> [3,] "A" "D"
> [4,] "A" "E"
> [5,] "A" "F"
> [6,] "A" "G"
> [7,] "B" "C"
> [8,] "B" "D"
> [9,] "B" "E"
> [10,] "B" "F"
> [11,] "B" "G"
> [12,] "C" "D"
> [13,] "C" "E"
> [14,] "C" "F"
> [15,] "C" "G"
> [16,] "D" "E"
> [17,] "D" "F"
> [18,] "D" "G"
> [19,] "E" "F"
> [20,] "E" "G"
> [21,] "F" "G"
>
>
> Bill Venables
> CSIRO Laboratories
> PO Box 120, Cleveland, 4163
> AUSTRALIA
> Office Phone (email preferred): +61 7 3826 7251
> Fax (if absolutely necessary): +61 7 3826 7304
> Mobile: +61 4 8819 4402
> Home Phone: +61 7 3286 7700
> mailto:Bill.Venables at csiro.au
> http://www.cmis.csiro.au/bill.venables/
>
> -----Original Message-----
> From: r-help-bounces at r-project.org
[mailto:r-help-bounces at r-project.org]
> On Behalf Of aiminy at iastate.edu
> Sent: Thursday, 15 November 2007 2:51 PM
> To: r-help at r-project.org
> Subject: [R] generate combination set
>
> I have a set data={A,B,C,D,E,F,G}
> I want to choose 2 letter from 8 letters, i.e. generate the
combination
> set
> for choose 2 letters from 8 letters.
> I want to get the liking:
> combination set={AB,AC,AD,....}
> Does anyone konw how to do in R.
>
> thanks,
>
> Aimin
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
--
Adrian Dusa
Romanian Social Data Archive
1, Schitu Magureanu Bd
050025 Bucharest sector 5
Romania
Tel./Fax: +40 21 3126618 \
+40 21 3120210 / int.101
More information about the R-help
mailing list