2012-10-15 23 views

回答

3

?'&&'你可以找到

& and && indicate logical AND and | and || indicate logical OR. 
The shorter form performs elementwise comparisons in much the same 
way as arithmetic operators. The longer form evaluates left to right 
examining only the first element of each vector. Evaluation proceeds 
only until the result is determined. The longer form is appropriate 
for programming control-flow and typically preferred in if clauses. 

那麼可能是你正在尋找&,而不是&&。看到這些例子,其中兩個條件進行評估:

# Case 1 
a<- 2 
b <- 4 

if(a!=0 & b/a>1){ 
    print('Hello World') 
} else{ 
    print("one or both conditions not met") 
} 
[1] "Hello World" 

# Case 2 
a<- 2 
b <- 1 

if(a!=0 & b/a>1){ 
    print('Hello World') 
} else{ 
    print("one or both conditions not met") 
} 
[1] "one or both conditions not met" 


# Case 3 
a<- 0 
b <- 1 

if(a!=0 & b/a>1){ 
    print('Hello World') 
} else{ 
    print("one or both conditions not met") 
} 
[1] "one or both conditions not met" 
+0

如果你讓第二個條件拋出一個錯誤,並顯示你的哪些情況不拋出錯誤,這個例子會更有用(我認爲),從而清楚地顯示出短路。 –

+0

謝謝@CarlWitthoft,非常有幫助的評論。我已經編輯了我的答案。 –

+0

當然是它所需要的'&&'版本。 'b/a'不會在'a = 0'的R中產生錯誤,它會產生'Inf',它可以與有限值進行比較而沒有問題。 – James

5

R還短路&&||運營商時,第二個參數並不需要進行評估。例如(這裏x不存在)

> if (exists('x') && x < 3) { print('do this') } else { print ('do that') } 
[1] "do that" 
0

或者使用短路陳述,如果這些都不夠清晰,因爲它們或者你可以只換你多if語句行成一個函數。以下是一些可視化的僞代碼。

如果(存在( 「user_set_variable」)){如果(user_set_variable < 3){ ...}}

然後可以:

var<- "user_set_variable" 'let var be your variable for this 
if(exists(var) && var < 3) 
{ 'do stuff } 

或做到這一點:

'function definition 
Function boolean IsValidVar(variable) 
{ 
    if(exists(var)) 
    { 
     if(var < 3) 
     { return true; }} 
    return false; 
} 

然後你的程序看起來像這樣:

var<- "user_set_variable" 'let var be your variable for this 
if(IsValidVar(var)) 
{ 'do stuff } 

這真的只是你的呼叫,看起來很簡單。

相關問題