【发布时间】:2018-08-09 17:57:52
【问题描述】:
假设我有以下数据集:
set.seed(42)
test <- data.frame(event_id = stringi::stri_rand_strings(1000, 2, '[A-Z]'), person_id = floor(runif(1000, min=0, max=500)))
>head(test)
event_id person_id
1 EP 438
2 IX 227
3 AV 212
4 GX 469
5 QF 193
6 MM 222
我想将其转换为邻接数据集,其中行和列是 person_id,值是这些人出现的 event_id 总数。
我试着做这样的事情:
adjacency_df <- test %>%
select('event_id', 'person_id') %>%
melt('event_id', value.name = 'invitee_id') %>%
dcast(invitee_id~invitee_id, fun.aggregate = n_distinct, value.var = 'event_id')
但是在尝试将其转换为邻接矩阵,然后计算不是对角项的非零值的总数,如下所示:
#convert to a matrix, and rename rownames
adjacency_matrix <- as.matrix(sapply(adjacency_df[, -1], as.numeric))
rownames(adjacency_matrix) <- colnames(adjacency_matrix)
#identify if only the diagonal of the matrix is non-zero
all(adjacency_matrix[lower.tri(adjacency_matrix)] == 0, adjacency_matrix[upper.tri(adjacency_matrix)] == 0)
我知道所有非对角线值都为零。
> all(adjacency_matrix[lower.tri(adjacency_matrix)] == 0, adjacency_matrix[upper.tri(adjacency_matrix)] == 0)
[1] TRUE
最有效的方法是什么(注意数据集包含 200 万个观测值)?
我已经尝试了 cmets 部分中建议的技术,并在我的实际数据集上得到以下错误:
adjacency_df <- crossprod(table(test)
Error in table(adjacency_df) :
attempt to make a table with >= 2^31 elements
所以我需要一个更好的方法
【问题讨论】:
-
看看这个问题:stackoverflow.com/questions/13281303/…。 A5C1D2H2I1M1N2O1R2T1 的回答提到了
crossprod(table(df)) -
请参阅编辑。我尝试过crossprod方法,但效果不佳。
-
igraph库是否满足您的需求?即,类似library(igraph) ; g <- graph_from_edgelist(as.matrix(test), directed = F) ; V(g)$type <- V(g)$name %in% test$event_id ; as_adj(bipartite_projection(g, which = "false"))
标签: r