Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

loops - If Else statements in R - Unexpected else in else

I have an assignment to sort 3 numbers in a vector by R only using if, else statements. I have changed parenthesis quite a bit but continue to get the "unexpected else in else" error in console

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)
question from:https://stackoverflow.com/questions/65641838/if-else-statements-in-r-unexpected-else-in-else

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The error is on the line 8 from the end.

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...