从此数据框df
group from to weight
1 1 Joey Joey 1
2 1 Joey Deedee 1
3 1 Deedee Joey 1
4 1 Deedee Deedee 1
5 2 Johnny Johnny 1
6 2 Johnny Tommy 1
7 2 Tommy Johnny 1
8 2 Tommy Tommy 1
可以像这样创建
df <- structure(list(group = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), from =
structure(c(2L, 2L, 1L, 1L, 3L, 3L, 4L, 4L), .Label = c("Deedee",
"Joey", "Johnny", "Tommy"), class = "factor"), to = structure(c(2L, 1L,
2L, 1L, 3L, 4L, 3L, 4L), .Label = c("Deedee", "Joey", "Johnny",
"Tommy"), class = "factor"), weight = c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L)), .Names = c("group", "from", "to", "weight"), class = "data.frame",
row.names = c(NA, -8L))
可以使用Matrix包
获得稀疏矩阵mat
mat <- sparseMatrix(i = as.numeric(df$from), j = as.numeric(df$to), x =
df$weight, dimnames = list(levels(df$from), levels(df$to)))
看起来像这样:
4 x 4 sparse Matrix of class "dgCMatrix"
Deedee Joey Johnny Tommy
Deedee 1 1 . .
Joey 1 1 . .
Johnny . . 1 1
Tommy . . 1 1
如何使用 df$group
创建稀疏子矩阵而不减少原始矩阵维度?
结果应该是这样的:
4 x 4 sparse Matrix of class "dgCMatrix"
Deedee Joey Johnny Tommy
Deedee 1 1 . .
Joey 1 1 . .
Johnny . . . .
Tommy . . . .
第一个想法
如果我将数据框子集化并创建子矩阵
df1 <- subset(df, group == 1)
mat1 <- sparseMatrix(i = as.numeric(df1 $from), j = as.numeric(df1 $to),
x = df1 $weight)
结果是2 x 2稀疏矩阵。这不是一个选择。除了“丢失两个节点”之外,我还必须过滤要用作维度名称的因子级别。
技巧可能是在创建矩阵时不会丢失因素。
第二个想法
如果我将df$weight
设置为零,我不感兴趣并创建子矩阵
df2 <- df
df2[df2$group == 2, 4] <- 0
mat2 <- sparseMatrix(i = as.numeric(df2$from), j = as.numeric(df2$to), x
= df2$weight, dimnames = list(levels(df$from), levels(df$to)))
矩阵具有正确的维度,我可以轻松地将因子级别作为维度名称,但矩阵现在包含零:
4 x 4 sparse Matrix of class "dgCMatrix"
Deedee Joey Johnny Tommy
Deedee 1 1 . .
Joey 1 1 . .
Johnny . . 0 0
Tommy . . 0 0
这也不是一个选项,因为行规范化会创建NaN
,当我将矩阵转换为图形并执行网络分析时,我遇到了麻烦。
这里,技巧可能是从稀疏矩阵中删除零?但是如何?
在任何情况下,解决方案必须尽可能高效,因为矩阵变得非常大。
答案 0 :(得分:1)
基本上是你的第一个想法:
mat1 <- sparseMatrix(i = as.numeric(df1$from), j = as.numeric(df1$to),
x = df1$weight,
dims = c(length(levels(df$from)), length(levels(df$to))),
dimnames = list(levels(df$from), levels(df$to)))
#4 x 4 sparse Matrix of class "dgCMatrix"
# Deedee Joey Johnny Tommy
#Deedee 1 1 . .
#Joey 1 1 . .
#Johnny . . . .
#Tommy . . . .