On Thu, 2006-11-09 at 16:24 -0600, Marc Schwartz wrote: > On Thu, 2006-11-09 at 22:32 +0100, Peter Dalgaard wrote: > > [EMAIL PROTECTED] 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)]))
Speaking of aging neurons, that should be: do.call("cbind", sapply(2:ncol(A), function(x) A[, x - 1] + A[, x:ncol(A)])) I accidentally left that last 'mat' in there from testing... Marc ______________________________________________ R-help@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.