Re: [R] lower triangle

About this list Date view Thread view Subject view Author view Attachment view

From: Douglas Bates (bates@stat.wisc.edu)
Date: Sat 21 Dec 2002 - 07:33:13 EST


Message-id: <6rznr0bfcm.fsf@bates5.stat.wisc.edu>


"Wilkinson, Mark" <Mark.Wilkinson@stjude.org> writes:

> I want to compute the lower triangle of a square matrix (optionally, sans
> diagonal). With for() loops I can do something like this:
>
> ## 5 by 5 matrix rtn
> for (j in 1:5) {
> for (k in 1:j) {
> if (j != k) { ## optional
> rtn[j, k] <- my.func(j, k)
> }
> }
> }
>
>
> I'd like to do this with apply(). Is there some way I can do this kind of
> 'short-circuit'?

It depends. If you can easily calculate a vector of values of
my.func(j,k) in the order in which the elements of the lower triangle
are stored you can do the assignment as

rtn[lower.tri(rtn)] <- vals

or

rtn[lower.tri(rtn, diag = TRUE)] <- vals

If you need to go through something like a double loop to calculate
the new values then this form of the replacement won't provide much of
an advantage.

See ?lower.tri and the lower.tri function itself.

______________________________________________
R-help@stat.math.ethz.ch mailing list
http://www.stat.math.ethz.ch/mailman/listinfo/r-help


About this list Date view Thread view Subject view Author view Attachment view

This archive was generated by hypermail 2.1.3 : Tue 01 Jun 2004 - 09:31:58 EST