[R] Algorithm needed

Peter Dalgaard p.dalgaard at biostat.ku.dk
Thu Nov 9 22:32:47 CET 2006


hbeltra at sas.upenn.edu writes:

> 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.

This should work in 2.4.0

n <- ncol(A)
cmb <- combn(n,2)
res <- A[,cmb[1,]] + A[,cmb[2,]]

-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-help mailing list