我有一个矩阵如下:(邻接矩阵)更好的方法来创建边缘列表矩阵使用邻接矩阵
R S K
A 1 1 0
B 0 1 0
C 1 0 0
D 1 0 0
E 0 0 1
F 0 0 1
的目的是得到一个正方形矩阵,这将有尺寸为行的数量和上述矩阵中的列。这个矩阵将使用上述矩阵填写(如果作为1,那么SA也应该是1),结果应该是这样的(边列表矩阵),
A B C D E F R S K
A 0 0 0 0 0 0 1 1 0
B 0 0 0 0 0 0 0 1 0
C 0 0 0 0 0 0 1 0 0
D 0 0 0 0 0 0 1 0 0
E 0 0 0 0 0 0 0 0 1
F 0 0 0 0 0 0 0 0 1
R 1 0 1 1 0 0 0 0 0
S 1 1 0 0 0 0 0 0 0
K 0 0 0 0 1 1 0 0 0
我写了下面的代码运行良好,我想知道是否有一种有效的方法来实现上述结果?
#READ THE FIRST DATA FRAME
df <- read.table(text = "R S K
1 1 0
0 1 0
1 0 0
1 0 0
0 0 1
0 0 1", header=TRUE)
#INPUT THE ROW NAMES IN df
rownames(df)<-LETTERS[1:6]
#INITIALIZE A SQUARE MATRIX WITH #ROWS=#COLUMNS=#(ROWS OF df)+#(COLUMNS OF df)
godmat<-matrix(0, nrow = sum(dim(df)), ncol= sum(dim(df)))
# ASSING ROW AND COLUMN NAMES
rownames(godmat) <- c(rownames(df),colnames(df))
colnames(godmat) <- c(rownames(df),colnames(df))
#fill the matrix using df
for (i in colnames(godmat))
for (j in colnames(godmat)) {
godmat[i,j]=tryCatch({ godmat[i,j]<-df[which(rownames(df)==i), which(colnames(df)==j)]}, error = function(cond) { return(0)})
#godmat[j,i]=godmat[i,j]
}
#fill the matrix using df by copying the elements already filled
for (i in colnames(godmat))
for (j in colnames(godmat)) {
godmat[j,i]=godmat[i,j]
}
谢谢,这就是我一直在寻找的东西。一个问题@akrun,将不参加将保持秩序完好?我知道这对您提供的解决方案没有任何影响。 – vivek
@vivek如果你想要一个自定义的订单,那么你可能不得不基于'match'或'factor'对其进行排序。 – akrun