使用稀疏矩阵可能可以解决您的问题。
# Load tiny toy data as edgelist
df <- data.frame(person =
c('Sam','Sam','Sam','Greg','Tom','Tom','Tom','Mary','Mary'), group =
c('a','b','c','a','b','c','d','b','d'), stringsAsFactors = F)
# Transform data to a sparse matrix
library(Matrix)
A <- spMatrix(nrow=length(unique(df$person)),
ncol=length(unique(df$group)),
i = as.numeric(factor(df$person)),
j = as.numeric(factor(df$group)),
x = rep(1, length(as.numeric(df$person))))
row.names(A) <- levels(factor(df$person))
colnames(A) <- levels(factor(df$group))
于做你实际上可以多possiblities投影,这里有两个:
# Use base r
Arow <- tcrossprod(A)
# Alternatively, if you want to project on the other mode:
Acol <- tcrossprod(t(A))
# Use the igraph package, which works with sparse matrices
library(igraph)
g <- graph.incidence(A)
# The command bipartite.projection does both possible projections at once
proj <- bipartite.projection(g)
#proj[[1]]
#proj[[2]]
你也可以读入数据,并通过使用data.table
做spMatrix
命令中的转变,这将加快这些行动。
UPDATE:
这里是一个更大的图形和一些内存基准测试的例子:
# Load packages
library(data.table)
library(igraph)
# Scientific collaboration dataset
# Descriptives as reported on https://toreopsahl.com/datasets/#newman2001
# mode 1 elements: 16726
# mode 2 elements: 22016
# two mode ties: 58595
# one mode ties: 47594
d <- fread("http://opsahl.co.uk/tnet/datasets/Newman-Cond_mat_95-99-two_mode.txt",
stringsAsFactors=TRUE, colClasses = "factor", header=FALSE)
# Transform data to a sparse matrix
A <- spMatrix(nrow=length(unique(d[, V1])),
ncol=length(unique(d[, V2])),
i = as.numeric(d[, V1]),
j = as.numeric(d[, V2]),
x = rep(1, length(as.numeric(d[, V1]))))
row.names(A) <- levels(d[, V1])
colnames(A) <- levels(d[, V2])
#To do the projection you have acutally multiple possiblities, here are two:
# Use base r
Arow <- tcrossprod(A)
# Alternatively, if you want to project on the other mode:
Acol <- tcrossprod(t(A))
这里是一个概述多少内存是怎么使用的,即稀疏矩阵的方法上的工作我笔记本电脑,但使用常规矩阵的做法确实给予了内存分配错误(即使从内存中删除Bcol
对象,然后调用垃圾收集器gc()
)
object.size(A) # Spare matrix: 3108520 bytes
object.size(Arow) # 2713768 bytes
object.size(Acol) # 5542104 bytes
# For comparison
object.size(B <- as.matrix(A)) # Regular matrix: 2945783320 bytes
object.size(Brow <- tcrossprod(B)) # 2239946368 bytes
object.size(Bcol <- tcrossprod(t(B))) # Memory allocation error on my laptop
嗨@majom,我尝试使用'graph.incidence'的mode参数,但是这并不控制投影的类型。根据帮助文件,'mode'“定义有向图中边的方向”。 使用'tcrossprod'提供了一个稀疏矩阵,我可以使用它来创建单模式图形,但是当我尝试这样做时,遇到了内存不足错误的同样问题。 – timothyjgraham
我的错,我刚刚添加了'bipartite.projection'命令,它执行'igraph'中的投影。解决内存不足问题的一个短期解决方案(虽然不是一个超级好的解决方案)是去EC2并获得一个大内存实例,并通过RStudio服务器进行分析:http://www.louisaslett.com/ RStudio_AMI/video_guide.html – majom
@timothyjgraham:我添加了一个示例,它显示了稀疏矩阵如何帮助您解决具体问题。这个例子中的网络规模是“可以忽略的”,尽管不如你的规模大。请尝试使用'rm()'和'gc()'在尝试不同的方法时检查您是否清理了内存。尝试新方法时,您也可以重新启动R会话。 – majom