将数据帧转换为R中的邻接矩阵

时间:2017-03-03 19:31:14

标签: r matrix social-networking network-analysis

我有一个数据集,其中包含多个重叠标准及其出现频率。我想使用R circlize 包将数据绘制为网络(和弦)图。我已经尝试将数据转换为邻接矩阵但没有成功。我可以将成对出现的观察值转换为矩阵。但是,如果有两个以上的标准,我就无法做到。  可以访问数据集here

数据看起来像这样

 criteria   criteria1   criteria2   criteria3   criteria3   Frequency
 None                   151
 G                  121
 BH                 108
 KBA                    4
 IBA    KBA             172
 AZE    KBA             1
 AZE    IBA KBA         3
 G  KBA             6
 G  IBA KBA         129
 G  AZE KBA         3
 G  AZE KBA IBA     7
 BH KBA             7
 BH IBA KBA         121
 BH AZE KBA         6
 BH AZE IBA KBA     15
 BH G               153
 BH G   KBA         32
 BH G   IBA KBA     200
 BH G   AZE         5
 BH G   AZE KBA     4
 BH G   AZE IBA KBA 44

1 个答案:

答案 0 :(得分:1)

您必须获得具有多个条件的行的所有对组合,并为其指定频率。然后你总结相同边的频率这是代码:

require(dplyr)

#Helper fucntion to get pairwise conbinations of criteria
getEdges <- function(x)
{
        # simplify the list
        v<-unlist(x);

        #Get the pairs and create a dataframe with the frequencies
        cb<-combn(v[1:length(v)-1],2, simplify=F);
        df<-data.frame(matrix(unlist(cb),ncol=2,byrow=T),frequency=as.integer(v[length(v)]),stringsAsFactors=F);

        return (df)
} 

#Get the pairs
edges <- lapply(split(df, seq(nrow(df))), getEdges)

#join the list into one dataframe
edges<-bind_rows(edges)

#Remove empty source and destination
edges <-edges[edges$X1!=""&edges$X2!="",]

#aggregate on edges
aggr <- aggregate(edges$frequency,by=list(edges$X1,edges$X2), FUN=sum)

数据框aggr是边缘列表。