[R] Algorithm needed
(Ted Harding)
Ted.Harding at nessie.mcc.ac.uk
Thu Nov 9 23:36:41 CET 2006
On 09-Nov-06 hbeltra at sas.upenn.edu wrote:
> I have a matrix of size "n" and I want to create a new one
> in which the columns are sums of the original matrix, with
> some order in the sums. For example, if matrix A has 4 columns,
> then the new matrix should have 6 columns with the following
> info from the columns of A: 1+2, 1+3, 1+4, 2+3, 2+4, 3+4.
> If matrix A has 5 columns, then the new matrix has 10 columns:
> 1+2, 1+3, 1+4, 1+5, 2+3, 2+4, 2+5, 3+4, 3+5, 4+5
>
> I thought of using a for loop:
> for (i in 1:n-1) {
> for (j in (i+1):n) {
> A[,i] + A[,j]
> }
> }
>
> but I don't know how to store the results so the new matrix has
> all the columns. I know the number of columns in the new matrix
> is given by n(n-1)/2.
>
> Any ideas? Thanks.
>
> Hiram
What an intriguing little question! The natural place to look for
all the combinations of 2 out of n (in the order you require) is
the function combn() in the package "combinat". Then I noticed
the argument "fun" in "?combn", which led to the following
(using a simple example):
library(combinat)
A<-cbind(c(1,2,3,4),c(1,3,5,7),c(1,4,7,10),c(1,5,9,13))
A
# [,1] [,2] [,3] [,4]
# [1,] 1 1 1 1
# [2,] 2 3 4 5
# [3,] 3 5 7 9
# [4,] 4 7 10 13
summit<-function(y)(rowSums(A[,y]))
S<-combn((1:4),2,fun=summit)
S
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] 2 2 2 2 2 2
# [2,] 5 6 7 7 8 9
# [3,] 8 10 12 12 14 16
# [4,] 11 14 17 17 20 23
so it looks as though this will do exactly what you want!
Thanks for asking the question: I hadn't spotted this
very useful feature of combn() before.
Best wishes,
Ted.
--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 09-Nov-06 Time: 22:36:38
------------------------------ XFMail ------------------------------
More information about the R-help
mailing list