# [R] Looping through all possible combinations of cases

Charles C. Berry cberry at tajo.ucsd.edu
Mon Jul 30 18:23:48 CEST 2007

```Lots of ways. Here is a simpler one.

?combn
?subset
?Subscript
?is.element
?apply
?paste - note the 'collapse' arg
?names - note the 'names(x) <- value' usage
?list
?unlist

then write a function that calc's the sum of variable given a vector of
names,

then figure out how to use apply on the result of combn() to feed a vector
of names to that function,

then figure out how to use paste() to turn a vector into a single string,

then figure out how to use apply()  with paste() to turn the vectors
of names into labels (like 'a:b' ) and 'names<-' to attach them to the
result of the earlier apply,

and finally wrap it all into a loop (for (i in 2:9) {...} saving the
results as res[[i]] <- value at teh end of each loop.

At the end 'unlist(res)' will produce a named vector of the sums with each
name indicating the people who contributed to it.

If you get stuck along the way report back to the list AFTER following the
suggestions in the POSTING GUIDE mentioned at the bottom of this email.

On Fri, 27 Jul 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
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help