如何将 tibble 转换为稀疏矩阵

how to cast a tibble to a sparse matrix

考虑一下这个简单的小标题

> data_frame(col1 = c(1,2,3), col2 = c(3,2,NA))
# A tibble: 3 x 2
   col1  col2
  <dbl> <dbl>
1     1     3
2     2     2
3     3    NA

将其转换为稀疏矩阵的最有效方法是什么? 我试过类似

> data_frame(col1 = c(1,2,3), col2 = c(3,2,NA)) %>% 
+   as(., 'sparseMatrix')
Error in as(from, "CsparseMatrix") : 
  no method or default for coercing “tbl_df” to “CsparseMatrix”

没有成功。按照建议尝试:

y <- purrr::reduce(cbind2, map(df, 'Matrix', sparse = TRUE))

也不行。

使用 tidyverse 有什么好主意吗? 谢谢!

这只是 the bounty-awarded answer 到上面链接的 post 的翻译,从基础 lapply/Reducepurrrmap/reduce。以前的答案使用:

Reduce(cbind2, lapply(x[,-1], Matrix, sparse = TRUE))

部分工作原理是数据框在技术上是列表,因此您可以使用 map 遍历数据框的列。这会产生两个稀疏矩阵,每列一个:

library(dplyr)
library(purrr)

df <- data_frame(col1 = c(1,2,3), col2 = c(3,2,NA))

map(df, Matrix::Matrix, sparse = T)
#> $col1
#> 3 x 1 sparse Matrix of class "dgCMatrix"
#>       
#> [1,] 1
#> [2,] 2
#> [3,] 3
#> 
#> $col2
#> 3 x 1 sparse Matrix of class "dgCMatrix"
#>        
#> [1,]  3
#> [2,]  2
#> [3,] NA

如果您随后使用 cbind2 对其进行缩减,则会得到一个稀疏矩阵。

map(df, Matrix::Matrix, sparse = T) %>% 
  reduce(cbind2)
#> 3 x 2 sparse Matrix of class "dgCMatrix"
#>          
#> [1,] 1  3
#> [2,] 2  2
#> [3,] 3 NA

reprex package (v0.2.1)

于 2018-10-16 创建