使用igraph超过两列

时间:2017-01-05 06:42:42

标签: r networking tree igraph

我有一个数据帧(df)如下。

V1 V2 V3 V4
 A B  C  D
 A G  R  T
 M A  R  H

我的要求是绘制从V1到V2到V3到V4的转换图。当我使用igraph命令

g = graph.data.frame(df)

我看到列V3和V4被删除了。有没有办法像这样构建转换图。

2 个答案:

答案 0 :(得分:3)

试试这个:

library(igraph)
df <- as.matrix(df)
# to transform the df to the format that igraph expects, following will suffice for your example 
df <- as.data.frame(rbind(df[,1:2], df[,2:3], df[,3:4]))
# if you want to make it generic try the following instead
# df <- as.data.frame(do.call(rbind, lapply(1:(ncol(df)-1), function(i) df[,i:(i+1)])))
g = graph.data.frame(df)
plot(g)

enter image description here

答案 1 :(得分:2)

我们可以通过在list中成对地对列进行子集,使用rbindlist(来自data.table)绑定数据集,转换为graph data.frame来执行此操作和plot

library(data.table)
library(igraph)
plot(graph.data.frame(rbindlist(lapply(seq(ncol(df)-1), function(i) df[i:(i+1)]))))

enter image description here

相关问题