[R] Construct a lower-triangular matrix

David Winsemius dwinsemius at comcast.net
Sat Oct 10 10:00:48 CEST 2015


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

> Thank you!
> 
> 	[[alternative HTML version deleted]]


David Winsemius
Alameda, CA, USA



More information about the R-help mailing list