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

From: Greg Snow <Greg.Snow_at_imail.org>
Date: Tue, 26 Feb 2008 13:48:10 -0700

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.
>
______________________________________________ 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.
Received on Tue 26 Feb 2008 - 20:52:07 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 26 Feb 2008 - 21:30:17 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive