R 通过单个列聚合稀疏矩阵
我有一个非常大的稀疏矩阵,看起来像:R 通过单个列聚合稀疏矩阵,r,R,我有一个非常大的稀疏矩阵,看起来像: client item_1 item_2 item_3.... item_n a 1 0 0 0 a 0 0 1 0 b 0 1 0 0 b 1 0 0 0 等等 我想按客户列汇总矩阵,以获得: client item_1 item_2 it
client item_1 item_2 item_3.... item_n
a 1 0 0 0
a 0 0 1 0
b 0 1 0 0
b 1 0 0 0
等等
我想按客户列汇总矩阵,以获得:
client item_1 item_2 item_3.... item_n
a 1 0 1 0
b 1 1 0 0
我曾尝试将其转换回密集矩阵,然后进行聚合,但遇到了内存问题
我的数据看起来像
new("dgCMatrix"
, i = c(0L, 1L, 2L, 3L, 0L, 3L, 2L, 1L)
, p = c(0L, 4L, 6L, 7L, 8L, 8L)
, Dim = 4:5
, Dimnames = list(NULL, c("client", "item_1", "item_2", "item_3", "item_n"
))
, x = c(1, 1, 2, 2, 1, 1, 1, 1)
, factors = list()
)
稀疏矩阵的矩阵乘法解决了这个问题(您的矩阵是b): 不同之处在于,客户机列现在可以作为行名称找到 通过单个阶乘变量聚合是更高级问题的特例,可通过包SSBtools中的函数解决:
clientFrame <- as.data.frame(as.matrix(b[, 1, drop = FALSE]))
# Two lines below are both same as fac2sparse(b[,1]) %*% b[,-1]
t(FormulaSums(clientFrame, ~client - 1)) %*% b[, -1]
t(Hierarchies2ModelMatrix(clientFrame, list(client = ""))) %*% b[, -1]
# Two lines below add overall totals
t(FormulaSums(clientFrame, ~client)) %*% b[, -1]
t(Hierarchies2ModelMatrix(clientFrame, list(client = "Total"))) %*% b[, -1]
clientFrame尝试aggregate(.~client,df1,sum)
或<代码>与(d,行和(d[-1],客户机))
。但请你把你的结构弄清楚一点好吗。它实际上是一个sparseMatrix类对象吗?既然你不能有字符变量,那么它是一个sparseMatrix,所以客户端变量是1,2,3,而不是a,b,c。聚合(.~client,df1,sum)不起作用,因为它是sparseMatrix。@deadasdreams;请您确认我添加到您的问题中的结构是否准确。如果没有,请更新。谢谢
clientFrame <- as.data.frame(as.matrix(b[, 1, drop = FALSE]))
# Two lines below are both same as fac2sparse(b[,1]) %*% b[,-1]
t(FormulaSums(clientFrame, ~client - 1)) %*% b[, -1]
t(Hierarchies2ModelMatrix(clientFrame, list(client = ""))) %*% b[, -1]
# Two lines below add overall totals
t(FormulaSums(clientFrame, ~client)) %*% b[, -1]
t(Hierarchies2ModelMatrix(clientFrame, list(client = "Total"))) %*% b[, -1]