# [R] Looping through all possible combinations of cases

Tue Jul 31 14:24:11 CEST 2007

```Here is another (simpler?) solution:

# your 1 column data is actually a vector
myvalues <- 1:10
names(myvalues) <- LETTERS[1:10]

# use the QCA package
library(QCA)
aa <- createMatrix(rep(2, length(myvalues)))

# set the number of combinations: 2, 3, 4 or whatever
combinations <- 2
sub.aa <- aa[rowSums(aa) == combinations, ]

result <- apply(sub.aa, 1, function(x)
sum(myvalues[x == 1]))
names(result) <- apply(sub.aa, 1, function(x)
paste(names(myvalues)[x == 1], collapse=""))

HTH,

On Friday 27 July 2007, Dimitri Liakhovitski 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

--