az-
az-

Reputation: 87

Listing all combinations in R

If I want to list all combinations I can use a nested loop:

for (int i = 1; i <= 5; i++) {
    for (int j = i + 1; j <= 5; j++) {
        System.out.println("Comparing " + i + " and " + j);
    }
}

How would I achieve the same functionality in R? I don't think I correctly understand the syntax for loops in R because this doesn't work (j keeps incrementing above 5).

for (i in 1:5) {
   for (j in i+1:5) {
   ...
   }
}

Upvotes: 3

Views: 169

Answers (2)

Benjamin
Benjamin

Reputation: 17279

If you're wanting to do anything beyond printing, this could be useful:

X <- expand.grid(i = 1:5,
                 j = 1:5)

X <- X[X$i <= X$j, ]

Upvotes: 3

R Thomas
R Thomas

Reputation: 156

The issue is with the order of the operations, the + operator is evaluated before the : operator. Try this.


for (i in 1:5) {
  for (j in i+(1:5)) {
    cat(paste0("i:", i, "; j: ", j, "\n"))
  }
}
#> i:1; j: 2
#> i:1; j: 3
#> i:1; j: 4
#> i:1; j: 5
#> i:1; j: 6
#> i:2; j: 3
#> i:2; j: 4
#> i:2; j: 5
#> i:2; j: 6
#> i:2; j: 7
#> i:3; j: 4
#> i:3; j: 5
#> i:3; j: 6
#> i:3; j: 7
#> i:3; j: 8
#> i:4; j: 5
#> i:4; j: 6
#> i:4; j: 7
#> i:4; j: 8
#> i:4; j: 9
#> i:5; j: 6
#> i:5; j: 7
#> i:5; j: 8
#> i:5; j: 9
#> i:5; j: 10

Upvotes: 1

Related Questions