我有一個矩陣如下:(鄰接矩陣)更好的方法來創建邊緣列表矩陣使用鄰接矩陣
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