1

Javaでは、そのようなことを行うのは非常に便利なことが多いことを私は知っています

if(a!=0 && b/a>1){
  ...;
}

最初の部分がすでに false の場合、Java は停止します。R はそれを行わず、時々エラーを生成します。だから:このコードを短くする可能性はありますか:

if(exists("user_set_variable")){
   if(user_set_variable < 3){
      ...
   }
}
4

3 に答える 3

5

また、2番目の引数を評価する必要がない場合、 Rは&&and演算子を短絡します。||たとえば(ここxには存在しません)

> if (exists('x') && x < 3) { print('do this') } else { print ('do that') }
[1] "do that"
于 2012-10-15T12:56:52.633 に答える
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.

&したがって、おそらく の代わりに を探しているでしょう&&。2 つの条件が評価されるこれらの例を参照してください。

# 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"
于 2012-10-15T13:02:11.523 に答える
0

それらがそのまま十分に明確である場合は短絡ステートメントを使用するか、複数の if ステートメント行を関数にラップすることができます。ビジュアルの擬似コードを次に示します。

if(exists("user_set_variable")){ if(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 }

シンプルに見えるのは、実際にはあなたの呼び出しです。

于 2012-10-17T13:38:28.930 に答える