6

Generate All Combinations of n Elements in R

 3 years ago
source link: https://yihui.org/cn/2007/04/generate-all-combinations-of-n-elements-in-r/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Generate All Combinations of n Elements in R

谢益辉 / 2007-04-16


Yesterday a member of COS asked how to generate all the elements of {all sets consisting of arbitrary combinations of n elements} in R and I didn’t know the function _combn() _then, so after a while I constructed a simple loop to fulfill this function (later I found this was wrong because it didn’t enumerate all possible combinations!):

> x = 1:5    # as an example, you may change this vector
> n = length(x)
> for (i in 1:n) {
    if (i == 1) {
        for (j in 1:n) {
            print(x[j])
        }
    }
    else {
        for (j in 1:(n - i + 1)) {
            for (k in (j + i - 1):n) {
                print(c(x[j:(j + i - 2)], x[k]))
            }
        }
    }
}

The output is:

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 1 2
[1] 1 3
[1] 1 4
[1] 1 5
[1] 2 3
[1] 2 4
[1] 2 5
[1] 3 4
[1] 3 5
[1] 4 5
[1] 1 2 3
[1] 1 2 4
[1] 1 2 5
[1] 2 3 4
[1] 2 3 5
[1] 3 4 5
[1] 1 2 3 4
[1] 1 2 3 5
[1] 2 3 4 5
[1] 1 2 3 4 5

Just now when I was reading the help text of the function choose(), I found that there had already been a function combn() in the package utils, which is very appropriate for this situation. For example:

> combn(x = 5, m = 3)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[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

So the problem in the beginning will be much easier.

A Leisure Graph Made in R Assignments, Lectures, Reports and Training

Disqus Utterances Preferences

© Yihui Xie 2005 - 2020

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK