[R] Odp: Looping through all possible combinations of cases

Petr PIKAL petr.pikal at precheza.cz
Mon Jul 30 16:02:16 CEST 2007


Hi

I am not sure about using loops but something like

colSums(combn(DATA[,1],2))
gives you sums of all pairs and

colSums(combn(DATA[,1],3))
sums of all triplets
etc.

if you want to know which ones they are just use combn on names.
e.g.

> y
  X1.5
a    1
b    2
c    3
d    4
e    5

> colSums(combn(y[,1],2))
 [1] 3 4 5 6 5 6 7 7 8 9

> combn(row.names(y),2)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] "a"  "a"  "a"  "a"  "b"  "b"  "b"  "c"  "c"  "d" 
[2,] "b"  "c"  "d"  "e"  "c"  "d"  "e"  "d"  "e"  "e" 

Regards

Petr

r-help-bounces at stat.math.ethz.ch napsal dne 27.07.2007 20:35:39:

> 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
> PLEASE do read the posting guide 
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list