2017-02-23 23 views
0

我很難試圖讓我的if語句運行我正在寫的代碼,我試圖分析每行真值的數量在稀疏矩陣(mat)中的行。如果語句在R-Markdown/R控制檯

counter=0 
geneCount=0 
columnIndex=-1 
cols=20 
rows=20 
for (col in 0:cols){ 
    columnIndex=columnIndex+1 
    for (row in 0:rows){ 
    for (col in 0:cols){ 
     if (mat[row,col] = TRUE){ 
     counter=counter+1 
     } 
     if(counter = 2){ 
     sigArray[columnIndex]=sigArray[columnIndex]+1 
     counter=0 
     next 
     } 
    } 
    } 
} 

我不斷收到錯誤消息:

Error: unexpected '=' in: 
" for (col in 0:cols){ 
     if (mat[row,col] =" 

第一個if語句。我曾嘗試使用雙等於,並沒有工作。

謝謝!

+2

嘗試''==代替。一個等號被解釋爲一個賦值(像'counter = 0')。想用「apply」函數族代替? –

+0

或者只是'if(mat [row,col]){'如果你的矩陣是由邏輯元素組成的。你也可以使用'if(isTRUE(mat [row,col])){'來保守。 – lmo

回答

1

至少有兩個問題。如您所想,第一個問題是,如果陳述是邏輯測試,並且需要平等測試操作員。您需要使用==來測試是否相等。第二個問題是行和列的R索引從1開始,而不是從0開始。因此,假設你確實有在你的數據集21點的行和列(即,使得0〜20會工作),我相信你應該修改你的語法是這樣的:

counter=0 
geneCount=0 
columnIndex=0 
cols=21 
rows=21 
for (col in 1:cols){ 
    columnIndex=columnIndex+1 
    for (row in 1:rows){ 
    for (col in 1:cols){ 
     if (mat[row,col] == TRUE){ 
     counter=counter+1 
     } 
     if(counter == 2){ 
     sigArray[columnIndex]=sigArray[columnIndex]+1 
     counter=0 
     next 
     } 
    } 
    } 
}