2017-04-02 34 views
0

我有一個矩陣,其中有10。例如:列表中有矩陣的某些值的位置

M1 = matrix(c(1, 0, 1, 0, 1, 0), nrow=2, ncol=3, byrow = TRUE) 
row.names(M1) <- c(100, 101) 
colnames(M1) <- c("A", "B", "C") 
M1 

    A B C 
100 1 0 1 
101 0 1 0 

現在我想在下面的語法矩陣創建的所有values=1列表:

"row name"."column name", value 

在這個例子中,我尋找的解決辦法是:

100.A, 1 
100.C, 1 
101.B, 1 

回答

1

試試這個:

x <- which(M1==1, arr.ind = TRUE) 
data.frame(COL=paste0(rownames(M1)[x[,1]], ".", colnames(M1)[x[,2]], ", ", 1)) 

#  COL 
#1 100.A, 1 
#2 101.B, 1 
#3 100.C, 1 
2

試試這個:

paste0(row.names(M1==1), ".", colnames(M1==1)) 

或者,如果你想添加1:

data.frame(result = paste0(row.names(M1==1), ".", colnames(M1==1), ", 1")) 

編輯:正確的,當1 1倍以上

result <- list() 
for (i in 1:nrow(M1)){ 
    result[[i]] <- data.frame(result = paste0(rep(row.names(M1)[i], length(colnames(M1)[M1[i,]==1])), ".", colnames(M1)[M1[i,]==1], ", 1")) 
} 
result <- do.call(rbind, result) 
result <- unique(result) 
+0

感謝您稱輸入!但我認爲如果矩陣具有另一種結構,它就無法工作。例如,如果一個柱子中有多個值等於1 –

相關問題