[R] How to transform the Matrix into the way I want it ???

David Winsemius dwinsemius at comcast.net
Tue Nov 10 00:15:27 CET 2009


On Nov 9, 2009, at 5:24 PM, Hongwei Dong wrote:

> Hi, R users,
>
> I'm trying to transform a matrix A into B (see below). Anyone knows  
> how to
> do it in R? Thanks.
>
> Matrix A (zone to zone travel time)
>
> zone z1 z2 z3  z1 0 2.9 4.3  z2 2.9 0 2.5  z3 4.3 2.5 0
>
 > ztz <- read.table(textConnection(" z1 z2 z3 \n z1 0 2.9 4.3 \n z2  
2.9 0 2.5 \n z3 4.3 2.5 0"), header=T)
 > ztz
     z1  z2  z3
z1 0.0 2.9 4.3
z2 2.9 0.0 2.5
z3 4.3 2.5 0.0

> B:
>
> from to time z1 z1 0 z1 z2 2.9 z1 z3 4.3 z2 z1 2.9 z2 z2 0 z2 z3 2.5  
> z3 z1
> 4.3 z3 z2 2.5 z3 z3 0

Now taking some liberties with coercion:

 > as.data.frame.table(ztz, responseName="Time")
   Var1 Var2 Time
1   z1   z1  0.0
2   z2   z1  2.9
3   z3   z1  4.3
4   z1   z2  2.9
5   z2   z2  0.0
6   z3   z2  2.5
7   z1   z3  4.3
8   z2   z3  2.5
9   z3   z3  0.0


Or perhaps:

 > data.frame(stack(as.data.frame(ztz)), From=colnames(ztz))
   values ind From
1    0.0  z1   z1
2    2.9  z1   z2
3    4.3  z1   z3
4    2.9  z2   z1
5    0.0  z2   z2
6    2.5  z2   z3
7    4.3  z3   z1
8    2.5  z3   z2
9    0.0  z3   z3

>
> The real matrix I have is much larger, with more than 2000 zones.  
> But I
> think it should be the same thing if I can transform A into B.
>
> Thanks.
>
> Garry
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list