ericksonsm at aol.com
2010-Aug-19 23:23 UTC
[R] Converting sparse matrix to data.frame in Matrix package
I am able to create a coordinate list sparse matrix this way: r = c(1,2,2,3,3) c = c(4,1,2,3,5) v = c(1,2,1,3,1) a = sparseMatrix(i=r,j=c,x=v) However, this results in an object that looks like this: a 3 x 5 sparse Matrix of class "dgCMatrix" [1,] . . . 1 . [2,] 2 1 . . . [3,] . . 3 . 1 How do I convert this object into a data.frame that would look like this: data.frame(a=c(0,2,0),b=c(0,1,0),c=c(0,0,3),d=c(1,0,0),e=c(0,0,1)) a b c d e 1 0 0 0 1 0 2 2 1 0 0 0 3 0 0 3 0 1 [[alternative HTML version deleted]]
Phil Spector
2010-Aug-19 23:35 UTC
[R] Converting sparse matrix to data.frame in Matrix package
This seems to work, although it eliminates the sparseness of the storage:> dimnames(a) = list(NULL,letters[1:5]) > as.data.frame(as.matrix(a))a b c d e 1 0 0 0 1 0 2 2 1 0 0 0 3 0 0 3 0 1 - Phil Spector Statistical Computing Facility Department of Statistics UC Berkeley spector at stat.berkeley.edu On Thu, 19 Aug 2010, ericksonsm at aol.com wrote:> > > > I am able to create a coordinate list sparse matrix this way: > > r = c(1,2,2,3,3) > c = c(4,1,2,3,5) > v = c(1,2,1,3,1) > > a = sparseMatrix(i=r,j=c,x=v) > > However, this results in an object that looks like this: > > a > > 3 x 5 sparse Matrix of class "dgCMatrix" > > [1,] . . . 1 . > [2,] 2 1 . . . > [3,] . . 3 . 1 > > How do I convert this object into a data.frame that would look like this: > > data.frame(a=c(0,2,0),b=c(0,1,0),c=c(0,0,3),d=c(1,0,0),e=c(0,0,1)) > > a b c d e > 1 0 0 0 1 0 > 2 2 1 0 0 0 > 3 0 0 3 0 1 > > > > [[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. >
Reasonably Related Threads
- Matrix: How create a _row-oriented_ sparse Matrix (=dgRMatrix)?
- Matrix: How create a _row-oriented_ sparse Matrix (=dgRMatrix)?
- Optimization algorithm to be applied to S4 classes - specifically sparse matrices
- What exactly is an dgCMatrix-class. There are so many attributes.
- What exactly is an dgCMatrix-class. There are so many attributes.