[R] built a lower triangular matrix from dataframe

nymphita sandrablazquezcabrera at gmail.com
Thu Feb 16 12:01:48 CET 2012


Hi David,

What an good solution. It works perfectly and it's really simple. 
(I only removed the "1+" in ncol=1+max(j), it already has 6 columns)
My result has been:

> df <- read.table(file="df.txt", head=T, sep="\t")
> df
   i j   k
1  1 2 5.2
2  1 3 9.1
3  1 4 8.0
4  1 5 2.3
5  1 6 8.4
6  2 3 6.6
7  2 4 7.4
8  2 5 7.1
9  2 6 5.5
10 3 4 4.1
11 3 5 3.9
12 3 6 9.2
13 4 5 8.5
14 4 6 7.6
15 5 6 9.9
> zmat <- with(df, matrix(0, ncol=max(j), nrow=1+max(i) ))
> # Then populate it with:
> zmat[with(df, cbind(i,j)) ] <- with(df, k) 
> zmat
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    0  5.2  9.1  8.0  2.3  8.4
[2,]    0  0.0  6.6  7.4  7.1  5.5
[3,]    0  0.0  0.0  4.1  3.9  9.2
[4,]    0  0.0  0.0  0.0  8.5  7.6
[5,]    0  0.0  0.0  0.0  0.0  9.9
[6,]    0  0.0  0.0  0.0  0.0  0.0

Great.

(I only inluded some png images in the post because the matrix looked more
neat to me that way...  It was my first time on Nabble. Thanks for calling
my attention on that, you are right)

--
View this message in context: http://r.789695.n4.nabble.com/built-a-lower-triangular-matrix-from-dataframe-tp4390813p4393591.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list