[R] Algorithm needed

Marc Schwartz marc_schwartz at comcast.net
Thu Nov 9 23:24:24 CET 2006


On Thu, 2006-11-09 at 22:32 +0100, Peter Dalgaard wrote:
> 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,]]

Peter, 

May I suggest that there be reciprocal "See Also"s added to ?expand.grid
and ?combn.

I had forgotten that this was added to 2.4.0, initially looked at the
former to begin a solution and then finally decided to propose:

  do.call("cbind", sapply(2:ncol(A), 
                   function(x) A[, x - 1] + A[, x:ncol(mat)]))

which is certainly more cumbersome, albeit a single line of code.

I then noted your reply, which of course sparked my aging neurons...

Thanks for the consideration.

Regards,

Marc



More information about the R-help mailing list