> -----Original Message----- > From: r-help-boun...@r-project.org > [mailto:r-help-boun...@r-project.org] On Behalf Of zhenjiang xu > Sent: Tuesday, August 10, 2010 11:03 AM > To: R-help@r-project.org > Subject: [R] matrix problem > > Hi, > > I have a file like this: > 1 2 0.1 > 2 3 0.2 > 3 1 0.3 > > And I want to read it to create a matrix like this: > [,1] [,2] [,3] > [1,] 0 0.1 0 > [2,] 0 0 0.2 > [3,] 0.3 0 0 > > How can I do it efficiently? Thanks.
Use a k-column matrix as a subscript into your k-dimensional output array. (k is 2 in your case.) E.g., 'input' is your matrix in a form that one can paste into an R session: > input <- cbind(c(1,2,3), c(2,3,1), c(.1,.2,.3)) > size <- max(input[,1:2]) # you may want something else here > output <- matrix(0.0, size, size) > output[input[,1:2]] <- input[,3] > output [,1] [,2] [,3] [1,] 0.0 0.1 0.0 [2,] 0.0 0.0 0.2 [3,] 0.3 0.0 0.0 Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com > -- > Best, > Zhenjiang > > [[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.