[R] how do I extract all possible combinations of rows from a column

Bert Gunter gunter.berton at gene.com
Tue Jan 21 22:15:10 CET 2014


... or combn() in utils.

which was the first hit when I googled on "finding combinations in R."

So moral: Use search engines before you post.

Cheers,
Bert

Bert Gunter
Genentech Nonclinical Biostatistics
(650) 467-7374

"Data is not information. Information is not knowledge. And knowledge
is certainly not wisdom."
H. Gilbert Welch




On Tue, Jan 21, 2014 at 12:57 PM, arun <smartpink111 at yahoo.com> wrote:
> Hi,
> May be this helps:
> library(gtools)
>
> as.data.frame(t(combinations(5,3,1:5)))
> #  V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
> #1  1  1  1  1  1  1  2  2  2   3
> #2  2  2  2  3  3  4  3  3  4   4
> #3  3  4  5  4  5  5  4  5  5   5
> A.K.
>
>
>
> For a column of data, I need to extract all possible unique
> combinations of 3 rows and combine the results into a data frame (as
> columns). So, for example, if I had a column called "test" that had five rows (the contents of which were the numbers 1:5) all possible
> combinations of 3 rows would be
> 1,2,3
> 1,2,4
> 1,2,5
> 1,3,4
> 1,3,5
> 1,4,5
> 2,3,4
> 2,4,5
> 2,4,5
> 3,4,5
>
> So for this example, R would extract all the combinations shown, and I would get a data frame that looked like this
> 1     1     1     1     1     1     2     2     2      3
> 2     2     2     3     3     4     3     3     4      4
> 3     4     5     4     5     5     4     5     5      5
>
> Note: I am not considering rearrangements of the same three rows
>  to be unique. In other words, the combinations 123, 132, 213, 231, 312,
>  321 are all the same as far as I am concerned. If it is not possible to
>  do it that way, it will still be helpful, but not quite as helpful.
> Thanks for the help!
>
> ______________________________________________
> 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.




More information about the R-help mailing list