r - 如何将 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 有什么好主意吗?谢谢!
解决方案
这只是对上面链接的帖子的赏金答案的翻译,从 base lapply
/Reduce
到purrr
'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 日创建
推荐阅读
- angular - 在 Angular SlickGrid 中切换语言后,切换过滤器行选项消失
- reactjs - 私有路由 React Router 和 Redux
- reactjs - react-vis 不绘制第二次( react-vis 仅绘制一次或 react-vis 仅第一次绘制)
- google-sheets - 如何在工作表的单独单元格中定义的多个范围之间生成数字数组?
- sql - 如何在 SQLITE 中返回外部行数组?
- c# - C# 理解为什么在 SSL 协议分配中使用按位或
- ios - iOS 应用程序在升级 POD 'Google-Mobile-Ads-SDK' 后终止。崩溃日志显示 - “GADMediaContent setDelegate”无法识别选择器
- node.js - ReactJS 和 NodeJS 项目
- javascript - 为什么这个 javascript 计算器不起作用?
- hibernate - Hibernate pooled vs pooled-lo id 生成器