[R] Nested for loops
David Winsemius
dwinsemius at comcast.net
Tue Jul 14 13:56:38 CEST 2009
On Jul 14, 2009, at 2:25 AM, Michael Knudsen wrote:
> On Tue, Jul 14, 2009 at 8:20 AM, Michael
> Knudsen<micknudsen at gmail.com> wrote:
>
>> What do you mean? It looks a like a very general solution to me.
>
> Just got an email suggesting using the functions col and row. For
> example
>
> temp = matrix(c(1:36),nrow=6)
> which(col(temp)>row(temp))
>
> This gives the indices (in the matrix viewed as a vector) of the
> above-diagonal entries.
>
If you want the entries it would then be:
temp[ col(temp) > row(temp) ]
But more simply:
> temp[ upper.tri(temp) ]
[1] 7 13 14 19 20 21 25 26 27 28 31 32 33 34 35
>
If you want the row and column numbers then:
> row(temp)[ col(temp) > row(temp)]
[1] 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
> col(temp)[ col(temp) > row(temp) ]
[1] 2 3 3 4 4 4 5 5 5 5 6 6 6 6 6
Any solution that uses col and row will create two additional matrices
of the same size as the original at least for the duration of the
operation.
For the sub-and super-diagonals:
http://finzi.psych.upenn.edu/Rhelp08/2009-March/191379.html
--
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
More information about the R-help
mailing list