[R] Construct a lower-triangular matrix

peter dalgaard pdalgd at gmail.com
Sat Oct 10 13:39:14 CEST 2015


> On 10 Oct 2015, at 10:49 , Berend Hasselman <bhh at xs4all.nl> wrote:
> 
>> 
>> On 10 Oct 2015, at 10:00, David Winsemius <dwinsemius at comcast.net> wrote:
>> 
>> 
>> On Oct 9, 2015, at 10:57 PM, Steven Yen wrote:
>> 
>>> Dear
>>> How do you construct a lower triangular matrix from a vector.
>>> 
>>> I want to make vector
>>> 
>>> a <- 1:10
>>> 
>>> into a triangular matrix
>>> 
>>> 1 0 0  0
>>> 2 3 0  0
>>> 4 5 6  0
>>> 7 8 9 10
>>> 
>> 
>> I'm not sure this method with logical indexing will be the most elegant:
>> 
>> ?lower.tri
>> ?col
>> 
>>> b=matrix(0, sqrt(10)+1,sqrt(10)+1)
>> 
>>> b[lower.tri(b)| row(b)==col(b)] <- 1:10
>>> b
>>    [,1] [,2] [,3] [,4]
>> [1,]    1    0    0    0
>> [2,]    2    5    0    0
>> [3,]    3    6    8    0
>> [4,]    4    7    9   10
>> 
> 
> That doesn’t seem to be what the OP wanted.
> 
> This should do it.
> 
> a <- 1:10
> C <- matrix(0, sqrt(length(a))+1,sqrt(length(a))+1)
> i.upr <- which(upper.tri(C, diag = TRUE), arr.ind=TRUE)
> C[i.upr] <- a
> t(C)
> 
> resulting in
> 
>     [,1] [,2] [,3] [,4]
> [1,]    1    0    0    0
> [2,]    2    3    0    0
> [3,]    4    5    6    0
> [4,]    7    8    9   10
> 
> I found this here: http://stackoverflow.com/questions/24472060/indexing-upper-or-lower-triangle-in-matrix-with-diagonal

It's crossing the creek a couple of times too many, though. This'll do:

> M <- matrix(0,4,4)
> M[upper.tri(M,TRUE)] <- 1:10 
> t(M)
     [,1] [,2] [,3] [,4]
[1,]    1    0    0    0
[2,]    2    3    0    0
[3,]    4    5    6    0
[4,]    7    8    9   10

I'm also not buying the sqrt(length(a))+1 bit --- floor(2*length(a)) is more like it.

(The generic answer is "with some care". In particular, avoid being trapped by column-major storage layout and by in/excluding the diagonal.)

-pd

> 
> Berend
> 
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.

-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list