首页 > 解决方案 > 如何将 tibble 转换为稀疏矩阵

问题描述

考虑这个简单的小标题

> 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 有什么好主意吗?谢谢!

标签: rdplyrsparse-matrixpurrr

解决方案


这只是对上面链接的帖子的赏金答案的翻译,从 base lapply/Reducepurrr's map/ 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 包(v0.2.1)于 2018 年 10 月 16 日创建


推荐阅读