有关R关系网络图中init.igarph的生成



关系网络分析中init.igarph()函数建立关系网络

数据集如下:

 

网络关系分析基础概念

 

 

如用户a和c有一个关系,把该关系记为edges(a,c)

权重weight()衡量两个不同样本点的直接关系大小

距离g()衡量两个不同样本点的间接关系大小

某一点的度degree衡量该点与整个网络的联系程度

1、数据处理

> from<-c("a","a","e","b","b","c","d","d","d","f")

> to<-c("c","e","c","e","c","d","g","g","f","d")

> data<-data.frame(from,to)

读取每个样本点的名称:

> data[,1] [1] a a e b b c d d d fLevels: a b c d e f

> unique(data[,1])                #元素去重

[1] a e b c d fLevels: a b c d e f

> labels<-union(unique(data[,1]),unique(data[,2]))   #合并函数进行合并

> labels

[1] "a" "e" "b" "c" "d" "f" "g"

建立点标识号向量ids,把样本名称作为元素名称

> ids<-1:length(labels)

> ids

[1] 1 2 3 4 5 6 7

> names(ids)<-labels   #映射关系

> ids

a e b c d f g 1 2 3 4 5 6 7 

把数据框data转换为矩阵

> from<-as.character(data[,1])

> to<-as.character(data[,2])

> ids[from]          #from映射过来

a a e b b c d d d f 1 1 2 3 3 4 5 5 5 6 

> edges<-matrix(c(ids[from],ids[to]),nc=2)

> edges     

 [,1] [,2] [1,]    1    4 [2,]    1    2 [3,]    2    4 [4,]    3    2 [5,]    3    4 [6,]    4    5 [7,]    5    7 [8,]    5    7 [9,]    5    6[10,]    6    5

2、建立一个空的关系网络(没有定义任何点和线)

> library("igraph", lib.loc="E:/R-3.1.3/R-3.1.3/library")

> g<-graph.empty(directed=F)                 #无向图(没有箭头)

3、添加点

> g<-add.vertices(g,length(labels))   #添加lengthlabels)个点vertices

> V(g)$label=labels                      #为各个点添加名称信息

添加线

> g<-add.edges(g,t(edges))        #这里的edges要先转置才能输入

 

4、把重复线合并,并把重复次数作为权重weight

> E(g)$weight<-count.multiple(g)           #计算网络g中每条线的重复数

> E(g)$weight 

[1] 1 1 1 1 1 1 2 2 2 2

> g<-simplify(g,remove.multiple=TRUE,                   #函数把重复的线删除

remove.loops=TRUE,

edge.attr.comb='mean')                               #使用重复的次数更新线权重

> E(g)$weight

[1] 1 1 1 1 1 1 2 2

 

用函数init.igraph就建立了一个完整的关系网络g

> init.igraph<-function(data,dir=F,rem.multi=T){

 lables<-union(unique(data[,1]),unique(data[,2]))

 ids<-1:length(lables);names(ids)<-labels

 from<-as.character(data[,1]);to<-as.character(data[,2])

 edges<-matrix(c(ids[from],ids[to]),nc=2)

 g<-graph.empty(directed=dir)

 g<-add.vertices(g,length(labels))

 V(g)$labels=labels

 g<-add.edges(g,t(edges))

 if(rem.multi){

 E(g)$weight<-count.multiple(g)

 g<-simplify(g,remove.multiple=TRUE,remove.loops=TRUE,edge.attr.comb='mean')

 }

 g

 }

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值