How can create a sparse matrix out of outer function in R?

In my code, the outer function outputs a matrix. Is it possible to make that output sparse matrix? I could convert this output matrix to a sparse matrix, but I want to do something like outer(......, sparse=T) rather than first have the dense matrix then conversion. Because I have very large data. My code and short sample vectors are below. I have read all the related posts but can`t figure it out.

> # myvec is a vector of length 100. 
> # mycol is a column vector of length 10.

myvec<-c( 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 1, 0, 2, 1, 2, 1, 3, 2, 2, 1, 0, 1, 2, 1, 0, 2, 1, 2, 1, 3, 2, 2, 1, 0,1, 
          2, 2, 3, 1, 2, 1, 0, 2, 1, 2, 1,0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 1, 0, 2, 1, 2, 1, 3, 2, 2, 1, 0, 1, 2,
          1, 0, 2, 1, 2, 1, 3, 2, 2, 1, 0,1, 2, 2, 3, 1, 2, 1, 0, 2, 1, 2, 1,0, 1, 1, 2, 1, 2, 2, 3)


mycol<-c(-15.07,-7.64, -15.48, -18.59, -12.35, -10.44, -11.45, -18.49, -15.24, -13.23)
> 
> 
> 
> res<-outer(1:length(mycol), 1:length(mycol),function(i,j)
> {ifelse(myvec > 1, 0, ifelse(myvec == 1, (mycol[j]-mycol[i])/(1-exp(-(mycol[j]-mycol[i]))),
>                                                       ifelse(myvec ==0, 1, myvec)))})

I have also tried to create a sparse matrix from scratch using row, col, value triplets, my code is below. But because the entry (resvec) length is 100, the sparse matrix is created but only using the first 10 of the entries to the diagonals and the rest of the off-diagonal elements are zero. But I wanted to write all 100 entries to their locations.

Many thanks in advance.

resvec<- as.vector(res)

matSparse <- sparseMatrix(
  i = 1:length(mycol), 
  j = 1:length(mycol), 
  x = resvec,
  dims = c(length(mycol),length(mycol)), 
  dimnames = list(index,index)
)


Read more here: https://stackoverflow.com/questions/66268515/how-can-create-a-sparse-matrix-out-of-outer-function-in-r

Content Attribution

This content was originally published by kutlus at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: