> -----Original Message----- > From: r-help-boun...@r-project.org > [mailto:r-help-boun...@r-project.org] On Behalf Of Hongwei Dong > Sent: Monday, November 09, 2009 2:24 PM > To: R-help Forum > Subject: [R] How to transform the Matrix into the way I want it ??? > > 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 > > 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
Try data.frame(From=rownames(A)[row(A)], To=colnames(A)[col(A)], Time=as.vector(A)) You probably do not want a matrix because all of its elements must have the same type, forcing Time to be character instead of numeric. E.g., > A<-rbind(Anacortes=c(Anacortes=0,Seattle=90,"Mount Vernon"=20), + Seattle=c(Anacortes=80, Seattle=0, "Mount Vernon"=60), + "Mount Vernon"=c(Anacortes=20,Seattle=70,"Mount Vernon"=0)) > data.frame(From=rownames(A)[row(A)], To=colnames(A)[col(A)], Time=as.vector(A)) From To Time 1 Anacortes Anacortes 0 2 Seattle Anacortes 80 3 Mount Vernon Anacortes 20 4 Anacortes Seattle 90 5 Seattle Seattle 0 6 Mount Vernon Seattle 70 7 Anacortes Mount Vernon 20 8 Seattle Mount Vernon 60 9 Mount Vernon Mount Vernon 0 Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com > > 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@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. > ______________________________________________ R-help@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.