Cosine similarity between columns of two sparse matrices

Thanks for continuing. Question

quote="kongcav, post:3, topic:162119"]
For a given sample, only a fraction of rows contain non-zero values
[/quote]

I'm not sure of this, because all rows have some non-zero values. Do you mean *all non-zero values?

(BTW: you can avoid having to take screenshots with a reprex. See the FAQ.)

library(Matrix)
q_mat <- new("dgeMatrix",
  Dim = 5:6, Dimnames = list(NULL, NULL), x = c(
    -2.5770364012495,
    0, 0, 2.54694632803317, 3.64904120269736, -3.02261588200774,
    0, 0, 0, 0, -2.04654404048837, -3.63879581531711, 0, 0, 0, 0,
    0, 0, -2.81866286398189, -3.66797842833383, 0, 0, 0, 0, 2.98110600049609,
    -2.19280397979525, 0, -2.8424060546161, -2.48547660452864, 0
  ),
  factors = list()
)

r_mat <- new("dgeMatrix",
  Dim = 5:6, Dimnames = list(NULL, NULL), x = c(
    -2.5770364012495,
    0, 0, 2.54694632803317, 3.64904120269736, -3.02261588200774,
    0, 0, 0, 0, -2.04654404048837, -3.63879581531711, 0, 0, 0, 0,
    0, 0, -2.81866286398189, -3.66797842833383, 0, 0, 0, 0, 2.98110600049609,
    -2.19280397979525, 0, -2.8424060546161, -2.48547660452864, 0
  ),
  factors = list()
)
r_mat <- new("dgeMatrix",
  Dim = c(5L, 10L), Dimnames = list(NULL, NULL),
  x = c(
    -3.4504049913605, 0, 0, 0, 0, 3.5394727773655, 0, 0,
    4.33940192113412, -5.86883647596701, 0, 2.33910643895182,
    0, -3.33773525083209, 2.26799438858444, 0, 0, 0, -3.27905564209673,
    0, 0, 0, 0, -3.42744251080144, 0, 0, 5.19680319250943, 0,
    0, 0, 0, 0, 0, 0, 3.15324351349785, 0, 0, 0, 0, 3.31553663832521,
    2.22957836928008, 0, 4.02176939483578, 0, 0, 0, 0, 2.21073872189316,
    0, 0
  ), factors = list()
)

cosine_mat <- qlcMatrix::cosSparse(q_mat, r_mat)
#> as(<dgeMatrix>, "dgCMatrix") is deprecated since Matrix 1.5-0; do as(., "CsparseMatrix") instead

rowSums(q_mat)
#> [1] -9.839000 -3.638796 -2.842406 -2.757193  2.962169
rowSums(r_mat)
#> [1]  2.318646  7.535910  6.232508 -5.704831  2.867938
rowSums(cosine_mat)
#> [1]  0.21030735  0.07880903 -1.27007299 -0.06901164  1.76275287  0.06055197