[R] lower triangle
Douglas Bates
bates at stat.wisc.edu
Fri Dec 20 21:34:02 CET 2002
"Wilkinson, Mark" <Mark.Wilkinson at 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.
More information about the R-help
mailing list