I 'm using the function below to put the items of a vector in an ascending order.
InOrder <- function(vector){
le <- length(vector)
for (j in c(2:le)){
key <- vector[j]
i <- j-1
while (i>0 & vector[i]>key){
vector[i+1] <- vector[i]
i <- i-1
}
vector[i+1] <- key
}
vector
}
I have those vectors:
MyVector1 <- c(2,4,3,8,9)
MyVector2 <- c(5,4,3,8,9)
As you can see InOrder()
function works fine with MyVector1
:
MyVectorOrd1 <- InOrder(MyVector1)
MyVectorOrd1
[1] 2 3 4 8 9
but not with MyVector2
:
MyVectorOrd2 <- InOrder(MyVector2)
Error in while (i > 0 & vector[i] > key) { : argument is of length zero
What am I doing wrong? I think that condition MyVector2[1]>MyVector2[2]
causes that problem, but I don't know why.
Thanks' in avance!
PS: I 've read this question, but I couldn't find the problem in my code.