首页 > 解决方案 > if else 语句连接 - R

问题描述

这是一个非常常见的问题:12345,但我什至找不到我的问题的答案。

If a == 1, then do X.
If a == 0, then do Y.
If a == 0 and b == 1, then do Z.

只是为了解释一下:if else 语句必须执行Yifa==0无论b. 但是 ifb == 1a == 0,Z将对已经由Y.

我当前的代码及其错误:

if (a == 1){
X
} else if(a == 0){
Y
} else if (a == 0 & b == 1){ 
Z}

Error in !criterion : invalid argument type

标签: rif-statement

解决方案


else仅当先前if 未发生时才会发生。

当你说

但是 ifb == 1a == 0,Z将对已经完成的那些做额外的改变Y

然后你有两个选择:

## Option 1: nest Z inside Y
if (a == 1){
  X
} else if(a == 0){
  Y
  if (b == 1){ 
    Z
  }
}


## Option 2: just use `if` again (not `else if`):
if (a == 1) {
  X
} else if(a == 0) {
  Y
}

if (a == 0 & b == 1) {  
  Z
}

真的,你根本不需要任何else东西。

## This will work just as well 
## (assuming that `X` can't change the value of a from 1 to 0
if (a == 1) {
  X
}

if (a == 0) {
  Y
  if (b == 1){ 
    Z
  }
}

通常else,当您想要一个“最终”操作时需要,该操作仅在没有使用之前的if选项时才完成,例如:

# try to guess my number between 1 and 10
if (your_guess == 8) {
  print("Congratulations, you guessed my number!")
} else if (your_guess == 7 | your_guess = 9) {
  print("Close, but not quite") 
} else {
  print("Wrong. Not even close!")
}

在上面,else它很有用,因为我不想列举用户可能输入的所有其他可能的猜测(甚至是错误的输入)。如果他们猜到 8,他们就赢了。如果他们猜 7 或 9,我告诉他们他们很接近。其他的,不管是什么,我只是说“错”。

注意:这对于一般的编程语言都是正确的。它不是 R 独有的。

但是,由于这是在 R 标签中,我应该提到 R 有if{}else{}and ifelse(),它们是不同的。

  • if{}(并且可选else{})评估单个条件,您可以运行代码来根据该条件执行任何操作{}
  • ifelse()是一个矢量化函数,它的参数是test, yes, no. 计算test结果为 TRUE 和 FALSE 值的布尔向量。yesno参数必须是与 长度相同的test向量。结果将是一个长度与 相同的向量,test对应的值为yes(when testis TRUE) 和no(when testis FALSE)。

推荐阅读