将长数据结构转换为宽矩阵结构

Turn a long data structure to a wide matrix structure

我确实有以下数据结构...

      ID value

1   1        1
2   1       63
3   1        2
4   1       58
5   2        3
6   2        4
7   3       34
8   3       25

现在我想把它变成一种二元数据结构。每个具有相同值的ID都应该有一个关系。

我尝试了几个选项并且:

df_wide  <- dcast(df, ID ~ value)

...让我走了很长一段路...

   ID 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 39 40
1     1001 0 0 0 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
2     1006 0 0 0 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
3     1007 1 0 0 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  1  1  0  0  0  0  0  0  0  0  0  0  0  2  0  0
4     1011 0 0 0 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  1  0  0  0  0  0  0  0  0  0  0  0  0  0  0
5     1018 1 0 0 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
6     1020 0 0 0 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  1  0  0  0  0  0  0  0  0  0  0  0  0  0
7     1030 0 0 1 0 0 0 0 0 0  1  1  0  0  0  0  0  0  0  0  0  0  0  0  0  0  1  0  0  0  0  1  0  0  0  0  0  0  0  0
8     1036 0 0 0 0 0 0 0 0 0  0  0  0  1  0  0  0  0  0  1  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0

现在我的主要问题是将其转换为适当的矩阵以从中获取 igraph 对象。

df_wide_matrix <- data.matrix(df_wide)

df_aus_wide_g <- graph.edgelist(df_wide_matrix ,directed = TRUE)

不要让我到那里...

我也试过把它转化成邻接矩阵...

df_wide_matrix <- get.adjacency(graph.edgelist(as.matrix(df_wide), directed=FALSE))

...但是也没用

如果您想在具有相同值的所有 ID 之间创建一条边,请改为尝试类似的方法。首先 merge 数据框由 value 放到自身上。然后,删除 value 列,并删除所有重复的(无向)边或只是点。最后,转换为 two-column 矩阵并创建边。

res <- merge(df, df, by='value', all=FALSE)[,c('ID.x','ID.y')]
res <- res[res$ID.x<res$ID.y,]
resg <- graph.edgelist(as.matrix(res))