如何基于相关性建立网络?

时间:2015-10-02 08:48:09

标签: r networking

我有一个像下面这样的矩阵

data <- replicate(30, rnorm(30)) 

我想建立一个像这个图像的网络 http://www.forwardprogress.net/data-steps-effective-relationship-marketing-dean-delisle/

当然是变量的名称(在这种情况下是V1到V30)

有没有办法在R?中做到这一点?

由于

1 个答案:

答案 0 :(得分:1)

你的问题非常不明确。但是这样的事情应该让你开始:

# Generate some toy data
data <- replicate(30, rnorm(30)) 

library("igraph")  # Load the igraph package

corr <- cor(data)  # Create weighted adjencency/correlation matrix

# Create a weighted complete graph from the correlation matrix
g <- graph.adjacency(corr, mode = "undirected", weighted = TRUE, diag = FALSE)

# Chose the layout function
custom.layout <- function(g, ...) {
  # layout.drl(g, weights = E(g)$weight, ...) # For bigger graphs
  layout.fruchterman.reingold(g, weights = E(g)$weight, ...)
}

查看?layout.fruchterman.reingold和其他布局功能以调整布局。

# Format edges
E(g)$cor <- E(g)$weight
E(g)$weight <- abs(E(g)$cor)
E(g)$color <- ifelse(E(g)$cor < 0, "blue", "red")
E(g)$width <- 3*atanh(E(g)$weight)

# Format vertices
V(g)$size <- 3*abs(rowSums(corr))
V(g)$color <- "grey"
V(g)$label.color <- "black"
V(g)$label <- ""

# Do the plot
plot(g, layout = custom.layout)

Imgur

现在它看起来与您呈现的图形不太相似。首先,由于我们模拟玩具数据的方式,我们不期望任何“枢纽” - 一切都只是噪音。其次,布局高度依赖于布局功能。 第三,这只是为了让您了解如何自定义图形和布局。