[R] Summing up diagonals w/o for-loop

Greg Snow Greg.Snow at imail.org
Tue Feb 26 21:48:10 CET 2008


Does this do what you want?

> d <- col(mat) - row(mat)
> tapply( mat, d, sum )

Hope this helps,

-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
(801) 408-8111
 
 

> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Camarda, 
> Carlo Giovanni
> Sent: Tuesday, February 26, 2008 1:32 PM
> To: r-help at stat.math.ethz.ch
> Subject: [R] Summing up diagonals w/o for-loop
> 
> Dear R-users,
> 
> is there any way to sum up the elements of the "diagonals" of 
> a matrix without using a for-loop? While there is a simple 
> way over rows and columns, I don't see a straightforward 
> multiplication for the diagonals, am I too demanding? Or, 
> more likely, I'm lack some algebra trick? Is there any 
> R-function that can deal with this problem w/o loop?
> 
> Actually I would need to sum up just the upper diagonals.
> 
> Here a simple, but general, example for presenting the problem. 
> 
> Thanks in advance for any help,
> Carlo Giovanni Camarda
> 
> m <- 7
> n <- 5
> mat <- matrix(1:35, n, m)
> ones.r <- rep(1,n)
> ones.c <- rep(1,m)
> # sum over the rows
> sum.r <- mat%*%ones.c
> # sum over the cols
> sum.c <- t(mat)%*%ones.r
> # sum over the diags
> sum.d <- numeric(m+n-1)
> sum.d[1] <- mat[n,1]
> sum.d[m+n-1] <- mat[1,m]
> for(i in 2:n){
>     sum.d[i] <- sum(diag(mat[(n+1-i):n,1:i])) } for(i in 2:(m-1)){
>     sum.d[i+n-1] <- sum(diag(mat[,i:m])) }
> 
> 
> 
> ----------
> This mail has been sent through the MPI for Demographic 
> ...{{dropped:10}}
> 
> ______________________________________________
> R-help at r-project.org 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