r语言 - 从邻接矩阵重建二元数据帧的最有效过程是什么



对于我认为这是一个相当简单的问题,我深表歉意。不幸的是,虽然我在这里的搜索返回了许多从二元数据帧制作邻接矩阵的结果,但我还没有遇到任何相反的过程 - 从邻接矩阵创建二元数据帧。

这是我在 R 中处理的 xls 文件的子集:

ccode           2       20      31     40      41      42   
    year        2010    2010    2010   2010    2010    2010 
        abbrev  USA     CAN     BHM    CUB     HAI     DOM  
2   2010    USA 0       1       1      1       1       1    
20  2010    CAN 1       0       0      1       1       1    
31  2010    BHM 1       1       0      1       1       0    
40  2010    CUB 1       1       1      0       1       1    
41  2010    HAI 1       1       1      1       0       1    
42  2010    DOM 1       1       0      1       1       0    
51  2010    JAM 1       1       0      1       0       0    

我希望它看起来像这样:

ccode   ccode2  year    Value       
2       20      2010    1   
2       31      2010    1
2       40      2010    1        
...    
20      31      2010    0     
20      40      2010    1 
20      41      2010    1       
...       

执行此类转换需要哪些 R 包/代码?

对于那些希望访问完整数据的人来说,它是DIPCON 3.0数据库,可以在这里找到:https://www.volgy.org/projects-and-data

path = "DIPCON_3.0.xlsx"# Put the correct path to your file
library(readxl) 
sheets = excel_sheets(path)
my_read = function(x){
  dat = read_excel(path,x)
  c_names = 1:4# The column names-also same as the row names
  col_names = do.call(paste,data.frame(t(dat[c_names,-c_names])))
  row_names = do.call(paste,dat[-c_names,c_names])
  dat1 = as.table(matrix(as.numeric(unlist(dat[-c_names,-c_names])),
                nrow(dat)-4,dim=list(row_names,col_names)))
  d = data.frame(dat1)
  l = nrow(d)
  proto = data.frame(ccode=numeric(l),Year=numeric(l),C1=character(l),C2=character(l))
  m = do.call(cbind,lapply(d[2:1],function(x) strcapture("(\d+) (\d+) (\w+) (\w+)",x,proto)))
  cbind(m,d[3])
}
my_read(sheets[1])

最新更新