我知道在 Java 中做这样的事情通常很方便
if(a!=0 && b/a>1){
...;
}
当第一部分已经为假时,Java 停止。R 不这样做,有时会产生错误。所以:是否有可能使这段代码更短:
if(exists("user_set_variable")){
if(user_set_variable < 3){
...
}
}
当不需要评估第二个参数时, R 还会使&&
and运算符短路。||
例如(这里x
不存在)
> if (exists('x') && x < 3) { print('do this') } else { print ('do that') }
[1] "do that"
从?'&&'
你可以找到
& 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"
如果它们足够清楚,请使用短路语句,或者您可以将多个 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 }
这真的只是你的电话看起来很简单。