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)
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)
I have been able to correct this by moving "else if" part of the statement right in front of the else and this works. Unfortunately, unclear on the paradigm
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])}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.