# [R] Looping through all possible combinations of cases

jim holtman jholtman at gmail.com
Mon Jul 30 21:36:59 CEST 2007

```Here is how to do it for 2; you can extend it:

> # test data
> n <- 100
> x <- data.frame(id=sample(letters[1:4], n, TRUE), values=runif(n))
> # get combinations of 2 at a time
> comb.2 <- combn(unique(as.character(x\$id)), 2)
> for (i in 1:ncol(comb.2)){
+     cat(sprintf("%s:%s %f\n",comb.2[1,i], comb.2[2,i],
+         sum(x\$value[x\$id %in% comb.2[,i]])))
+ }
c:d 25.259988
c:b 21.268737
c:a 21.250933
d:b 26.013253
d:a 25.995450
b:a 22.004198

On 7/27/07, Dimitri Liakhovitski <ld7631 at gmail.com> wrote:
> Hello!
>
> I have a regular data frame (DATA) with 10 people and 1 column
> ('variable'). Its cases are people with names ('a', 'b', 'c', 'd',
> 'e', 'f', etc.). I would like to write a function that would sum up
> the values on 'variable' of all possible combinations of people, i.e.
>
> 1. I would like to write a loop - in such a way that it loops through
> each possible pair of cases (i.e., ab, ac, ad, etc.) and sums up their
> respective values on 'variable'
>
> 2. I would like to write a loop - in such a way that it loops through
> each possible trio of cases (i.e., abc, abd, abe, etc.) and sums up
> their respective values on 'variable'.
>
> 3.  I would like to write a loop - in such a way that it loops through
> each possible quartet of cases (i.e., abcd, abce, abcf, etc.) and sums
> up their respective values on 'variable'.
>
> etc.
>
> Then, at the end I want to capture all possible combinations that were
> considered (i.e., what elements were combined in it) and get the value
> of the sum for each combination.
>
> How should I do it?
> Thanks a lot!
> Dimitri
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> and provide commented, minimal, self-contained, reproducible code.
>

--
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?

```