2013-11-20 36 views
0

我想在R中實現以下事情,但我是新的R和我的代碼不起作用。嵌套如果陳述在R

我有矩陣A,我沒有座標變化。 我想寫兩個函數: 1)給出矩陣的元素,給出座標 2)給出座標給定數。 僞代碼是正確的,唯一的問題是我的語法。有人可以糾正它嗎?

f<- as.numeric(readline(prompt="Please enter 10 to get coordinate of number,and 20 to get the number > ")); 
if(p==10){ 
# give the number, given coordinates 
i<- as.numeric(readline(prompt="Pleae enter i cordinate > ")); 
j<- as.numeric(readline(prompt="Pleae enter j cordinate > ")); 
if (i>0&j<0) return A[5+i,5+j] 
if (i>0&j>0) return A[5+i,5+j] 
if (i<0&j>0) return A[5+i,5-j] 
if (i<0&j<0) return A[5+i,5-j] 



}else if (p==20){ 
#give the cordinate, given number 

coordinate <- which(A==number) 
[i,j]<-A[2-coordinate[0],coordinate[1]-2] 
} 





} 
+1

我建議你的代碼減少再現您的問題最小,可以在C/P後執行R – Raffael

回答

1

警告:如果我或j是等於零?接下來,讓一個變量,它的二進制I,J,那就是十進制表示,

if(p==10){ 
x <- (i>0) + 2*(j>0) +1 
# x takes on values 1 thru 5. This is because switch requires nonnegative integer 

switch(x, 
    return A[5+i,5+j], 
    return A[5+i,5+j], 
    return A[5+i,5+j], 
    return A[5+i,5+j]) # change the +/- indices as desired 
}else{ 
#etc. 

最後,你應該做這樣的功能,而不是一個命令的集合。

編輯 - 我以前跳過這一點,但是:所以你需要修復的行了一些事情,你不能打電話的0指數[i,j]<-A[2-coordinate[0],coordinate[1]-2]

+0

所以,我該如何修復'[i,j] < - A [2座標[0],座標[1] -2]' – user2806363

+0

@ user2806363首先解釋您想要檢索哪個「座標」元素。現在「座標」是一系列標識「A」中的位置的數字,看起來「A」是一個矢量,而不是矩陣。您可能需要使用R語言進行一些輔導才能獲得成功。 –

0

的語法如下:

x <- 4 
if (x == 1 | x == 2) print("YES") 
+0

我不明白這對OP有何幫助。他在每種情況下返回不同的價值。 –

+0

OP:「唯一的問題是我的語法」。我因此顯示語法 – tagoma

+1

你必須爲微軟(谷歌的那個笑話) –