[R] Converting sparse matrix to data.frame in Matrix package
Phil Spector
spector at stat.berkeley.edu
Fri Aug 20 01:35:00 CEST 2010
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.
>
More information about the R-help
mailing list