gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 23:41:19 26 4
gpt4 key购买 nike

我有这样的数据:

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)

关于r - 计算每对列的相同行值以创建网络图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36900108/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com