如何将 tibble 转换为稀疏矩阵

ℕʘʘ*_*ḆḽḘ 1 r sparse-matrix dplyr purrr

考虑这个简单的小标题

\n\n
> data_frame(col1 = c(1,2,3), col2 = c(3,2,NA))\n# A tibble: 3 x 2\n   col1  col2\n  <dbl> <dbl>\n1     1     3\n2     2     2\n3     3    NA\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
> data_frame(col1 = c(1,2,3), col2 = c(3,2,NA)) %>% \n+   as(., \'sparseMatrix\')\nError in as(from, "CsparseMatrix") : \n  no method or default for coercing \xe2\x80\x9ctbl_df\xe2\x80\x9d to \xe2\x80\x9cCsparseMatrix\xe2\x80\x9d\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
y <- purrr::reduce(cbind2, map(df, \'Matrix\', sparse = TRUE))\n
Run Code Online (Sandbox Code Playgroud)\n\n

也不行。

\n\n

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

\n

cam*_*lle 5

这只是上面链接的帖子的赏金答案lapply的翻译,从 base /Reducepurrrs map/ reduce。之前的答案使用了:

Reduce(cbind2, lapply(x[,-1], Matrix, sparse = TRUE))
Run Code Online (Sandbox Code Playgroud)

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

Reduce(cbind2, lapply(x[,-1], Matrix, sparse = TRUE))
Run Code Online (Sandbox Code Playgroud)

如果然后用 减少它cbind2,就会得到一个稀疏矩阵。

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
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.2.1)于 2018-10-16 创建