【问题标题】:How to add sparse matrices with different column names in R?如何在 R 中添加具有不同列名的稀疏矩阵?
【发布时间】:2018-01-17 23:19:48
【问题描述】:

我有一个行数相同但列不同的稀疏矩阵列表。

这是一个玩具数据集:

library(dplyr)
library(Matrix)
ms <- list(
  m1 = data.frame(a = c(1, 10, 100), d = c(2, 20, 200), e = c(3, 30, 300)) %>% as.matrix %>% as("sparseMatrix"),
  m2 = data.frame(a = c(4, 40, 400), e = c(5, 50, 500), f = c(6, 60, 600), g = c(7, 70, 700)) %>% as.matrix%>% as("sparseMatrix"),
  m3 = data.frame(c = c(8, 80, 800), d = c(9, 90, 900)) %>% as.matrix%>% as("sparseMatrix")
)

我想按列添加ms 中的每个矩阵。这就是我目前的做法:

# get a list of unique columns
final_names <- sapply(ms, colnames) %>% unlist %>% unique

# create an empty sparseMatrix of those dimensions
final_matrix <- matrix(0, nrow = nrow(ms$m1), ncol = length(final_names)) %>% 
  set_colnames(final_names) %>% as("sparseMatrix")

# add the matrices by column
for(mat in ms) {
  current_colnames <- colnames(mat)
  final_matrix[, current_colnames] <- mat + final_matrix[, current_colnames]
}

这是我的输出:

final_matrix
3 x 6 sparse Matrix of class "dgCMatrix"
       a    d   e   f   g   c
[1,]   5   11   8   6   7   8
[2,]  50  110  80  60  70  80
[3,] 500 1100 800 600 700 800

这可行,但是当我在真实数据集上尝试时,我遇到了分段错误,因此必须有更好的方法来创建空稀疏矩阵或其他方法。有什么想法吗?

【问题讨论】:

  • 也许添加一个, drop = FALSEfinal_matrix[, current_colnames] 以防万一您有任何1 列矩阵。

标签: r matrix sparse-matrix


【解决方案1】:
NM = unique(unlist(lapply(ms, colnames)))
temp = do.call(cbind, ms)
sapply(NM, function(nm) rowSums(as.matrix(temp[,colnames(temp) %in% nm])))
#       a    d   e   f   g   c
#[1,]   5   11   8   6   7   8
#[2,]  50  110  80  60  70  80
#[3,] 500 1100 800 600 700 800

temp = do.call(cbind, lapply(ms, function(x) as.data.frame(as.matrix(x))))
sapply(split.default(temp, unlist(sapply(ms, colnames))), rowSums)
#       a   c    d   e   f   g
#[1,]   5   8   11   8   6   7
#[2,]  50  80  110  80  60  70
#[3,] 500 800 1100 800 600 700

【讨论】:

  • 谢谢!不幸的是,这导致了分配错误:Error: cannot allocate vector of size 39.2 Gb
  • 好的,我使用Matrix::rowSums: sapply(NM, function(nm) Matrix::rowSums(temp[, colnames(temp) %in% nm, drop = FALSE])) 修复了它。花了2:30小时,但它奏效了。谢谢!!
  • 如果输出也可以是稀疏矩阵,那就太好了。我尝试直接转换它,但我get a segfault
猜你喜欢
  • 2017-12-16
  • 2018-08-07
  • 2021-11-18
  • 2017-06-15
  • 2021-11-18
  • 2020-08-14
  • 1970-01-01
  • 2011-01-29
  • 1970-01-01
相关资源
最近更新 更多