[R] column permutation of sparse matrix
khai
ktluong71 at gmail.com
Wed Dec 21 21:32:30 CET 2011
Sorry. I erred somewhere in making the original M1 matrix using sampling call
in the spMatrix function. I still don't really understand why the matrix
values do not match exactly with M1 at x. If I regenerate M1 this way...
> i=c(1:5,5:1)
> j=c(1:5,2:6)
> x=rnorm(10,2)
> M1 <- spMatrix(nrow=5,ncol=6,i=i,j=j,x=x)
> M1
5 x 6 sparse Matrix of class "dgTMatrix"
[1,] 1.876193 . . . . 2.040574
[2,] . 1.032214 . . 1.786480 .
[3,] . . 1.716743 3.711979 . .
[4,] . . 2.534000 3.302921 . .
[5,] . 1.084763 . . 1.511992 .
Then the str(M1) makes sense and all the methods described so far appears to
work as expected.
> M1 at x
[1] 1.876193 1.032214 1.716743 3.302921 1.511992 1.084763 2.534000 3.711979
[9] 1.786480 2.040574
The solution is still not apparent to me though without doing a lapply.
spVecs <- lapply(1:nrow(M1), function(a)
{
nnz <- nnzero(M1[a,])
tmp <- as(M1[a,],'sparseVector')
tmp at x <- tmp at x[sample(nnz,nnz)]
return(tmp)
})
To get back a sparse matrix...I can do this.
x <- do.call(c,lapply(spVecs,function(v) v at x))
j= do.call(c,lapply(spVecs,function(v) v at i))
i = do.call(c,lapply(1:length(spVecs), function(n)
rep(n,length(spVecs[[n]]@i))))
permM1 <- sparseMatrix(i=i,j=j,x=x)
> permM1
5 x 6 sparse Matrix of class "dgCMatrix"
[1,] 2.040574 . . . . 1.876193
[2,] . 1.786480 . . 1.032214 .
[3,] . . 1.716743 3.711979 . .
[4,] . . 2.534000 3.302921 . .
[5,] . 1.511992 . . 1.084763 .
In this case, rows 3 and 4 remained unchanged. But now this takes a really
long time for a large sparse matrix.
Thanks for any advice.
--
View this message in context: http://r.789695.n4.nabble.com/column-permutation-of-sparse-matrix-tp4216726p4223079.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list