运维开发网
广告位招商联系QQ:123077622
 
广告位招商联系QQ:123077622

计算每对列的相同行值以创建网络图

运维开发网 https://www.qedev.com 2020-06-17 20:24 出处:网络 作者:运维开发网整理
我有这样的数据: dat <- data.frame( music = c("classical", "jazz", "baroque", "electronic", "ambient"), john = c(1,1,0,1,1), jeff = c(1,0,0,1,0), jane = c(0,1,1,0,0) ) music john jeff jane 1
我有这样的数据:

dat <- data.frame(
  music = c("classical", "jazz", "baroque", "electronic", "ambient"),
  john = c(1,1,0,1,1),
  jeff = c(1,0,0,1,0),
  jane = c(0,1,1,0,0)
)

       music john jeff jane
1  classical    1    1    0
2       jazz    1    0    1
3    baroque    0    0    1
4 electronic    1    1    0
5    ambient    1    0    0

并且想要绘制列上各个人之间的重叠图 – 他们在同一行中有多少次1?如果我可以访问此data.frame:

result <- data.frame(person1 = c("john", "john", "jeff"), person2 = c("jeff", "jane", "jane"), overlap = c(2, 1, 0))

  person1 person2 overlap
1    john    jeff       2
2    john    jane       1
3    jeff    jane       0

我可以创建我想到的图形:

library(igraph)
g <- graph.data.frame(result, directed = FALSE)
plot(g, edge.width = result$overlap * 3)

但我正在努力转换数据以计算每对列之间的行方向重叠.我怎样才能做到这一点?

可能更简单的方法是通过采用交叉积来创建图的邻接矩阵.然后,您可以直接阅读igraph.

library(igraph)

# Take the crossproduct: assumes unique music types in each row
# otherwise aggregate terms
m <- crossprod(as.matrix(dat[-1]))

# You could remove the diagonal terms here
# although it is useful to see the sum for each individual
# You can also remove it in igraph, as below
# diag(m) <- 0

# Create graph
# The weights are stored in E(g)$weight
g <- graph_from_adjacency_matrix(m, mode="undirected", weighted = TRUE)

# Remove edge loops
g <- simplify(g)

扫码领视频副本.gif

0

精彩评论

暂无评论...
验证码 换一张
取 消