【问题标题】:If Else statements in R - Unexpected else in elseR 中的 If Else 语句 - else 中的意外 else
【发布时间】:2021-01-09 10:58:39
【问题描述】:

我有一个任务,仅使用 if、else 语句按 R 对向量中的 3 个数字进行排序。我已经改变了很多括号,但在控制台中继续出现“unexpected else in else”错误

x <- c(200, 700, 1000)

if ((x[1] > x[2]) & (x[1] > x[3])) {
  if (x[2] > x[3]) {
    ord <- c(x[1], x[2], x[3])
  } else {
    ord <- c(x[1], x[3], x[2])
  }
}
else if ((x[2] > x[1]) & (x[2] > x[3]) {
  if (x[1] > x[3]) {
    ord <- c(x[2], x[1], x[3])
  } else {
    ord <- c(x[2], x[3], x[1])
  }
}
else if {
  (x[1] > x[2])
  ord <- c(x[3], x[1], x[2])
} else {
  ord <- c(x[3], x[2], x[2])
}
print(ord)

【问题讨论】:

  • 你的两个大括号是错误的。第 4 行中的一个属于第 3 行。下面的另一个 if 语句也是如此。
  • 嗨!你绝对应该遵循某种风格指南,比如this one。这真的很有帮助,特别是如果您刚刚开始编程。我现在已经把你的代码和它对齐了,也许你会发现现在调试代码会更容易一些?

标签: r loops if-statement indentation


【解决方案1】:

错误在最后的第 8 行。

x <- c(200, 700, 1000)

if ((x[1] > x[2]) & (x[1] > x[3])) {
  if (x[2] > x[3]) {
    ord <- c(x[1], x[2], x[3])
  }
  else {
    ord <- c(x[1], x[3], x[2])
  }
}
else if ((x[2] > x[1]) & (x[2] > x[3]) {
  if (x[1] > x[3]) {
    ord <- c(x[2], x[1], x[3])
  }
  else  {
    ord <- c(x[2], x[3], x[1])
  }
}
else if(x[1] > x[2]){ # I moved the following line here
  # (x[1] > x[2]) # this is a mistake
  ord <- c(x[3], x[1], x[2])
}
else {
  ord <- c(x[3], x[2], x[2])
}

print(ord)

【讨论】:

    【解决方案2】:

    我已经能够通过将语句的“else if”部分移动到 else 前面来纠正这个问题,这很有效。不幸的是,范式不清楚

    if((x[1]>x[2]) & (x[1]>x[3])){
       if(x[2]>x[3]){
          ord <- c(x[1],x[2],x[3])}
        else {ord <- c(x[1],x[3],x[2])}} else if((x[2]>x[1]) & (x[2]>x[3])){
        if(x[1]>x[3]){
              ord <- c(x[2],x[1],x[3])}
        else  {ord <- c(x[2],x[3],x[1])}} else if (x[1]>x[2]){
         ord <- c(x[3],x[1],x[2])} else {ord <- c(x[3],x[2],x[1])}
    

    【讨论】:

      最近更新 更多