有效地在R中加载稀疏矩阵 [英] Efficiently Load A Sparse Matrix in R

查看:84
本文介绍了有效地在R中加载稀疏矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法高效地将数据加载为R中的稀疏矩阵格式.

I'm having trouble efficiently loading data into a sparse matrix format in R.

这是我当前策略的一个(不完整的)示例:

Here is an (incomplete) example of my current strategy:

library(Matrix)
a1=Matrix(0,5000,100000,sparse=T)
for(i in 1:5000)
  a1[i,idxOfCols]=x

其中x通常在20左右.这效率不高,最终会减慢爬行速度.我知道有更好的方法,但不确定如何.有建议吗?

Where x is usually around length 20. This is not efficient and eventually slows to a crawl. I know there is a better way but wasn't sure how. Suggestions?

推荐答案

您可以一次填充所有矩阵:

You can populate the matrix all at once:

library(Matrix)
n <- 5000
m <- 1e5
k <- 20
idxOfCols <- sample(1:m, k)
x <- rnorm(k)

a2 <- sparseMatrix(
  i=rep(1:n, each=k),
  j=rep(idxOfCols, n),
  x=rep(x, k),
  dims=c(n,m)
)

# Compare
a1 <- Matrix(0,5000,100000,sparse=T)
for(i in 1:n) {
  a1[i,idxOfCols] <- x
}
sum(a1 - a2) # 0

这篇关于有效地在R中加载稀疏矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆